Esempio n. 1
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='RoleDetails',
            fields=[
                ('name',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('email',
                 models.EmailField(blank=True,
                                   default='',
                                   max_length=255,
                                   primary_key=True,
                                   serialize=False,
                                   unique=True)),
                ('password',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('mobile',
                 models.BigIntegerField(blank=True, default='', null=True)),
                ('gender',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('image',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('is_active', models.NullBooleanField(default=0)),
                ('otp',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('otp_time',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
                ('verify_link',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  null=True)),
            ],
        ),
        migrations.CreateModel(
            name='UserRole',
            fields=[
                ('role_id', models.AutoField(primary_key=True,
                                             serialize=False)),
                ('role_name',
                 models.CharField(blank=True,
                                  default='',
                                  max_length=255,
                                  unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='roledetails',
            name='role_id',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='backend_app.UserRole'),
        ),
    ]
Esempio n. 2
0
class Migration(migrations.Migration):

    initial = True

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

    operations = [
        migrations.CreateModel(
            name='Mail',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('subject', models.CharField(max_length=80)),
                ('body', models.TextField()),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('priority', models.IntegerField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='MailRecipient',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('recipient_id', models.BigIntegerField()),
                ('type',
                 models.SmallIntegerField(
                     choices=[(0,
                               'Character'), (1,
                                              'Corporation'), (2,
                                                               'Alliance')])),
                ('mail',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='recipients',
                                   to='eve_mail_queue.Mail')),
            ],
        ),
        migrations.CreateModel(
            name='MailSender',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('character',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='mail',
            name='sender',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to='eve_mail_queue.MailSender'),
        ),
    ]
Esempio n. 3
0
class Migration(migrations.Migration):

    initial = True

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

    operations = [
        migrations.CreateModel(
            name='user_info',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('account_id', models.IntegerField(unique=True)),
                ('acc_holder_name', models.CharField(max_length=100)),
                ('acc_holder_contact_no', models.IntegerField()),
                ('status',
                 models.CharField(default=None, max_length=9, null=True)),
                ('created_date', models.DateTimeField()),
                ('update_date',
                 models.DateTimeField(blank=True, default=None, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='vendor_information',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('vendor_id',
                 models.CharField(
                     default=vendor_process.models.increment_vendor_number,
                     editable=False,
                     max_length=20)),
                ('company_nick_name', models.CharField(max_length=254)),
                ('company_name_reg', models.CharField(max_length=254)),
                ('door_street', models.CharField(max_length=254)),
                ('locality', models.CharField(max_length=254, null=True)),
                ('state', models.CharField(max_length=254, null=True)),
                ('pincode', models.IntegerField()),
                ('primary_email', models.EmailField(max_length=254)),
                ('primary_contact_name',
                 models.CharField(max_length=100, null=True)),
                ('primary_contact_no',
                 models.BigIntegerField(default=0, null=True)),
                ('secondary_email', models.EmailField(max_length=254,
                                                      null=True)),
                ('secondary_contact_no',
                 models.BigIntegerField(default=0, null=True)),
                ('secondary_contact_name',
                 models.CharField(max_length=254, null=True)),
                ('gstin', models.CharField(max_length=15, null=True)),
                ('uin', models.CharField(blank=True, max_length=15,
                                         null=True)),
                ('insurance_no',
                 models.CharField(blank=True, max_length=50, null=True)),
                ('insurance_company',
                 models.CharField(blank=True, max_length=254, null=True)),
                ('expiry_date',
                 models.DateField(blank=True, default=None, null=True)),
                ('status',
                 models.CharField(default=None, max_length=9, null=True)),
                ('created_date', models.DateTimeField()),
                ('updated_date',
                 models.DateTimeField(blank=True, default=None, null=True)),
                ('account_id',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='user_address',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('entity_name',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=100,
                                  null=True)),
                ('email', models.EmailField(max_length=254)),
                ('door_street',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=50,
                                  null=True)),
                ('locality',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=50,
                                  null=True)),
                ('state',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=50,
                                  null=True)),
                ('pincode',
                 models.IntegerField(blank=True, default=None, null=True)),
                ('contact_no',
                 models.IntegerField(blank=True, default=None, null=True)),
                ('gstin',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=100,
                                  null=True)),
                ('uin',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=100,
                                  null=True)),
                ('insurance_no',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=100,
                                  null=True)),
                ('insurance_name',
                 models.CharField(blank=True,
                                  default=None,
                                  max_length=100,
                                  null=True)),
                ('expiry_date',
                 models.DateField(blank=True, default=None, null=True)),
                ('addr_identity', models.CharField(max_length=15)),
                ('created_date', models.DateTimeField()),
                ('updated_date',
                 models.DateTimeField(blank=True, default=None, null=True)),
                ('account_id',
                 models.ForeignKey(db_column='account_id',
                                   on_delete=django.db.models.deletion.CASCADE,
                                   to='vendor_process.user_info',
                                   to_field='account_id')),
            ],
        ),
    ]
Esempio n. 4
0
class PhoneNumber(models.Model):  # 开放的号码
    phone_number = models.BigIntegerField(default=0, primary_key=True)  # 号码
    is_achieved = models.BooleanField(default=False)  # 是否被预约
    id_reserved = models.BooleanField(default=False)  # 是否被预留
    user_name = models.CharField(max_length=20, null=True, blank=True)  # 预约人
    date = models.DateField(null=True, blank=True)
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('empresa', '0003_auto_20200209_2228'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('inventario', '0008_auto_20200216_1012'),
    ]

    operations = [
        migrations.CreateModel(
            name='Compra',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('estado', models.BooleanField(default=True)),
                ('creacion', models.DateTimeField(auto_now_add=True)),
                ('edicion', models.DateTimeField(auto_now=True)),
                ('codigo', models.IntegerField(verbose_name='Codigo')),
                ('observacion', models.CharField(blank=True, max_length=100, null=True, verbose_name='Observacion')),
                ('sub_total', models.FloatField(default=0, verbose_name='Sub Total')),
                ('descuento', models.FloatField(default=0, verbose_name='Descuento')),
                ('total', models.FloatField(default=0, verbose_name='Total')),
                ('empresa', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='empresa.Empresa', verbose_name='Empresa')),
            ],
            options={
                'verbose_name': 'Compra',
                'verbose_name_plural': 'Compras',
            },
        ),
        migrations.CreateModel(
            name='Proveedor',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('estado', models.BooleanField(default=True)),
                ('creacion', models.DateTimeField(auto_now_add=True)),
                ('edicion', models.DateTimeField(auto_now=True)),
                ('nombre', models.CharField(max_length=100, unique=True, verbose_name='Nombre')),
                ('direccion', models.CharField(blank=True, max_length=250, null=True, verbose_name='Direccion')),
                ('contacto', models.CharField(max_length=100, verbose_name='Contacto')),
                ('telefono', models.CharField(max_length=10, verbose_name='Telefono')),
                ('email', models.CharField(blank=True, max_length=250, null=True, verbose_name='Email')),
                ('user_create', django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('user_update', django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'Proveedor',
                'verbose_name_plural': 'Proveedores',
            },
        ),
        migrations.CreateModel(
            name='DetalleCompra',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('estado', models.BooleanField(default=True)),
                ('creacion', models.DateTimeField(auto_now_add=True)),
                ('edicion', models.DateTimeField(auto_now=True)),
                ('cantidad', models.BigIntegerField(default=0, verbose_name='Cantidad')),
                ('precio_compra', models.FloatField(default=0, verbose_name='Precio de compra')),
                ('sub_total', models.FloatField(default=0, verbose_name='Sub-Total')),
                ('descuento', models.FloatField(blank=True, default=0, null=True, verbose_name='Descuento')),
                ('total', models.FloatField(default=0, verbose_name='Total')),
                ('compra', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='compras.Compra', verbose_name='Compra')),
                ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='inventario.Producto', verbose_name='Producto')),
                ('user_create', django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('user_update', django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'Detalle Compra',
                'verbose_name_plural': 'Detalles Compra',
            },
        ),
        migrations.AddField(
            model_name='compra',
            name='proveedor',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='compras.Proveedor', verbose_name='Proveedor'),
        ),
        migrations.AddField(
            model_name='compra',
            name='user_create',
            field=django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='compra',
            name='user_update',
            field=django_userforeignkey.models.fields.UserForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL),
        ),
    ]
Esempio n. 6
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Boxes',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('weight', models.BigIntegerField()),
                ('price', models.DecimalField(decimal_places=2, max_digits=10)),
                ('amount', models.BigIntegerField()),
            ],
            options={
                'db_table': 'boxes',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Countries',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('country', models.CharField(max_length=50)),
            ],
            options={
                'db_table': 'countries',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Racks',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('max_weight', models.BigIntegerField()),
            ],
            options={
                'db_table': 'racks',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Suppliers',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
            ],
            options={
                'db_table': 'suppliers',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Warehouses',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('area', models.BigIntegerField()),
                ('address', models.CharField(max_length=100)),
            ],
            options={
                'db_table': 'warehouses',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='WarehouseSupplierRelationships',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
            ],
            options={
                'db_table': 'warehouse_supplier_relationships',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Weapons',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
            ],
            options={
                'db_table': 'weapons',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Workers',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
                ('phone', models.DecimalField(decimal_places=0, max_digits=10)),
                ('wage', models.DecimalField(decimal_places=2, max_digits=10)),
            ],
            options={
                'db_table': 'workers',
                'managed': False,
            },
        ),
    ]
Esempio n. 7
0
class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='AddrObj',
            fields=[
                ('ifnsfl', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsfl',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('ifnsul', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsul',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('okato', models.BigIntegerField(null=True, blank=True)),
                ('oktmo', models.BigIntegerField(null=True, blank=True)),
                ('postalcode',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('updatedate', models.DateField()),
                ('startdate', models.DateField()),
                ('enddate', models.DateField()),
                ('normdoc', models.UUIDField(null=True, blank=True)),
                ('aoguid', models.UUIDField(primary_key=True,
                                            serialize=False)),
                ('parentguid',
                 models.UUIDField(db_index=True, blank=True, null=True)),
                ('aoid', models.UUIDField(unique=True, db_index=True)),
                ('previd', models.UUIDField(null=True, blank=True)),
                ('nextid', models.UUIDField(null=True, blank=True)),
                ('formalname', models.CharField(db_index=True,
                                                max_length=120)),
                ('offname',
                 models.CharField(null=True, blank=True, max_length=120)),
                ('shortname', models.CharField(db_index=True, max_length=10)),
                ('aolevel', models.PositiveSmallIntegerField(db_index=True)),
                ('regioncode', models.CharField(max_length=2)),
                ('autocode', models.CharField(max_length=1)),
                ('areacode', models.CharField(max_length=3)),
                ('citycode', models.CharField(max_length=3)),
                ('ctarcode', models.CharField(max_length=3)),
                ('placecode', models.CharField(max_length=3)),
                ('streetcode', models.CharField(max_length=4)),
                ('extrcode', models.CharField(max_length=4)),
                ('sextcode', models.CharField(max_length=3)),
                ('code', models.CharField(null=True, blank=True,
                                          max_length=17)),
                ('plaincode',
                 models.CharField(null=True, blank=True, max_length=15)),
                ('actstatus', models.BooleanField(default=False)),
                ('centstatus', models.PositiveSmallIntegerField()),
                ('operstatus', models.PositiveSmallIntegerField()),
                ('currstatus', models.PositiveSmallIntegerField()),
                ('livestatus', models.BooleanField(default=False)),
            ],
            options={
                'ordering': ['aolevel', 'formalname'],
            },
        ),
        migrations.CreateModel(
            name='AddrObjIndex',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('aoguid', models.UUIDField()),
                ('aolevel', models.PositiveSmallIntegerField()),
                ('scname', models.TextField()),
                ('fullname', models.TextField()),
                ('item_weight', models.PositiveSmallIntegerField(default=64)),
            ],
        ),
        migrations.CreateModel(
            name='House',
            fields=[
                ('ifnsfl', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsfl',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('ifnsul', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsul',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('okato', models.BigIntegerField(null=True, blank=True)),
                ('oktmo', models.BigIntegerField(null=True, blank=True)),
                ('postalcode',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('updatedate', models.DateField()),
                ('startdate', models.DateField()),
                ('enddate', models.DateField()),
                ('normdoc', models.UUIDField(null=True, blank=True)),
                ('aoguid', models.UUIDField()),
                ('housenum',
                 models.CharField(null=True, blank=True, max_length=20)),
                ('eststatus', models.PositiveSmallIntegerField(default=0)),
                ('buildnum',
                 models.CharField(null=True, blank=True, max_length=10)),
                ('strucnum',
                 models.CharField(null=True, blank=True, max_length=10)),
                ('strstatus', models.PositiveSmallIntegerField()),
                ('houseguid',
                 models.UUIDField(primary_key=True, serialize=False)),
                ('houseid', models.UUIDField()),
                ('statstatus', models.PositiveSmallIntegerField()),
                ('counter', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='HouseInt',
            fields=[
                ('ifnsfl', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsfl',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('ifnsul', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsul',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('okato', models.BigIntegerField(null=True, blank=True)),
                ('oktmo', models.BigIntegerField(null=True, blank=True)),
                ('postalcode',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('updatedate', models.DateField()),
                ('startdate', models.DateField()),
                ('enddate', models.DateField()),
                ('normdoc', models.UUIDField(null=True, blank=True)),
                ('houseintid', models.UUIDField()),
                ('intguid', models.UUIDField(primary_key=True,
                                             serialize=False)),
                ('aoguid', models.UUIDField()),
                ('intstart', models.PositiveIntegerField()),
                ('intend', models.PositiveIntegerField()),
                ('intstatus', models.PositiveIntegerField()),
                ('counter', models.PositiveIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='LandMark',
            fields=[
                ('ifnsfl', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsfl',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('ifnsul', models.PositiveIntegerField(null=True, blank=True)),
                ('terrifnsul',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('okato', models.BigIntegerField(null=True, blank=True)),
                ('oktmo', models.BigIntegerField(null=True, blank=True)),
                ('postalcode',
                 models.PositiveIntegerField(null=True, blank=True)),
                ('updatedate', models.DateField()),
                ('startdate', models.DateField()),
                ('enddate', models.DateField()),
                ('normdoc', models.UUIDField(null=True, blank=True)),
                ('landid', models.UUIDField()),
                ('landguid', models.UUIDField(primary_key=True,
                                              serialize=False)),
                ('aoguid', models.UUIDField()),
                ('location', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='NormDoc',
            fields=[
                ('normdocid',
                 models.UUIDField(primary_key=True, serialize=False)),
                ('docname', models.TextField(null=True, blank=True)),
                ('docdate', models.DateField(null=True, blank=True)),
                ('docnum',
                 models.CharField(null=True, blank=True, max_length=20)),
                ('doctype', models.PositiveIntegerField()),
                ('docimgid', models.PositiveIntegerField(null=True,
                                                         blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='SocrBase',
            fields=[
                ('level',
                 models.PositiveSmallIntegerField(verbose_name='level')),
                ('scname', models.CharField(max_length=10, default=' ')),
                ('socrname', models.CharField(max_length=50, default=' ')),
                ('kod_t_st',
                 models.PositiveIntegerField(primary_key=True,
                                             serialize=False)),
                ('item_weight', models.PositiveSmallIntegerField(default=64)),
            ],
            options={
                'ordering': ['level', 'scname'],
            },
        ),
        migrations.CreateModel(
            name='Status',
            fields=[
                ('table',
                 models.CharField(primary_key=True,
                                  max_length=15,
                                  serialize=False)),
            ],
        ),
        migrations.CreateModel(
            name='Version',
            fields=[
                ('ver', models.IntegerField(primary_key=True,
                                            serialize=False)),
                ('date', models.DateField(null=True, blank=True,
                                          db_index=True)),
                ('dumpdate', models.DateField(db_index=True)),
                ('complete_xml_url', models.CharField(max_length=255)),
                ('complete_dbf_url', models.CharField(max_length=255)),
                ('delta_xml_url',
                 models.CharField(null=True, blank=True, max_length=255)),
                ('delta_dbf_url',
                 models.CharField(null=True, blank=True, max_length=255)),
            ],
        ),
        migrations.AddField(
            model_name='status',
            name='ver',
            field=models.ForeignKey(to='fias.Version'),
        ),
        migrations.AlterIndexTogether(
            name='socrbase',
            index_together=set([('level', 'scname')]),
        ),
        migrations.AlterIndexTogether(
            name='addrobj',
            index_together=set([('aolevel', 'shortname'),
                                ('shortname', 'formalname')]),
        ),
    ]
Esempio n. 8
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Crash',
            fields=[
                ('Checkout', models.NullBooleanField(default=False)),
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('PS_case', models.BigIntegerField(null=True)),
                ('PS_Case_ID', models.CharField(max_length=20, null=True)),
                ('DLD', models.CharField(blank=True, max_length=20, null=True)),
                ('Validated', models.CharField(max_length=20, null=True)),
                ('Date', models.CharField(blank=True, max_length=18, null=True)),
                ('Date_of_Crash', models.DateTimeField(blank=True, null=True)),
                ('County_Code', models.CharField(blank=True, max_length=6, null=True)),
                ('Route', models.CharField(blank=True, max_length=5, null=True)),
                ('Direction', models.CharField(blank=True, max_length=1, null=True)),
                ('Milepoint', models.CharField(blank=True, max_length=8, null=True)),
                ('Crash_Verified', models.NullBooleanField(default=False)),
                ('City', models.CharField(blank=True, max_length=20, null=True)),
                ('Exit_Number', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(999)])),
                ('Type', models.CharField(blank=True, max_length=2, null=True)),
                ('Ramp_ID', models.CharField(blank=True, max_length=4, null=True)),
                ('Case_Number', models.CharField(blank=True, max_length=20, null=True)),
                ('Crash_Severity', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(89)])),
                ('Nearest_City', models.CharField(blank=True, max_length=25, null=True)),
                ('Distance', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(5000)])),
                ('Manner_Collision', models.CharField(blank=True, max_length=2, null=True)),
                ('Main_Road_Name', models.CharField(blank=True, max_length=30, null=True)),
                ('Road_Junction_Feature', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Road_Jurisdiction', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('At_Intersection_With', models.CharField(blank=True, max_length=25, null=True)),
                ('First_Harmful_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Not_at_Intersection_Distance', models.CharField(blank=True, max_length=8, null=True)),
                ('Not_at_Intersection_Direction', models.CharField(blank=True, max_length=2, null=True)),
                ('Nearest_Intersection', models.CharField(blank=True, max_length=25, null=True)),
                ('Ref_Post_Distance', models.CharField(blank=True, max_length=8, null=True)),
                ('Ref_Post_Direction', models.CharField(blank=True, max_length=2, null=True)),
                ('Ref_Post_Description', models.CharField(blank=True, max_length=25, null=True)),
                ('Light_Condition', models.CharField(blank=True, max_length=2, null=True)),
                ('Weather_Condition', models.CharField(blank=True, max_length=2, null=True)),
                ('Road_Surface_Condition', models.CharField(blank=True, max_length=2, null=True)),
                ('Work_Zone_Related', models.CharField(blank=True, max_length=2, null=True)),
                ('Work_Zone_Worker_Present', models.CharField(blank=True, max_length=2, null=True)),
                ('Work_Zone_ID', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Work_Zone_Location', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Unconfirmed_Fatality_Report', models.CharField(max_length=4, null=True)),
                ('Narrative', models.TextField(blank=True, null=True)),
                ('QC_Comments', models.TextField(blank=True, null=True)),
                ('Motor_Carrier_Involved', models.CharField(blank=True, max_length=1, null=True)),
                ('CMV_Verified', models.NullBooleanField(default=False)),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now, null=True)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Locate',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False)),
                ('PS_Case_ID', models.CharField(max_length=20, null=True)),
                ('latitude', models.CharField(blank=True, max_length=22, null=True)),
                ('longitude', models.CharField(blank=True, max_length=22, null=True)),
                ('milepoint', models.CharField(blank=True, max_length=10, null=True)),
                ('route_number', models.CharField(blank=True, max_length=11, null=True)),
                ('type_road', models.CharField(blank=True, max_length=2, null=True)),
                ('direction', models.CharField(max_length=2, null=True)),
                ('exit_number', models.CharField(max_length=3, null=True)),
                ('ramp_ID', models.CharField(max_length=2, null=True)),
                ('county_ID', models.CharField(blank=True, max_length=10, null=True)),
                ('address', models.CharField(blank=True, max_length=100, null=True)),
                ('city', models.CharField(blank=True, max_length=30, null=True)),
                ('zip_code', models.CharField(blank=True, max_length=10, null=True)),
                ('event_date', models.DateTimeField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Person',
            fields=[
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('PS_case', models.BigIntegerField(null=True)),
                ('Name_Last', models.CharField(blank=True, max_length=25, null=True)),
                ('Name_First', models.CharField(blank=True, max_length=25, null=True)),
                ('Name_Middle', models.CharField(blank=True, max_length=25, null=True)),
                ('Sex', models.CharField(blank=True, max_length=1, null=True)),
                ('Date_Of_Birth', models.CharField(blank=True, max_length=10, null=True)),
                ('Age', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(125)])),
                ('Address_Street', models.CharField(blank=True, max_length=40, null=True)),
                ('Address_Street2', models.CharField(blank=True, max_length=40, null=True)),
                ('Address_City', models.CharField(blank=True, max_length=25, null=True)),
                ('Address_State', models.CharField(blank=True, max_length=2, null=True)),
                ('Address_Zip', models.CharField(blank=True, max_length=12, null=True)),
                ('Address_County', models.CharField(blank=True, max_length=3, null=True)),
                ('Phone', models.CharField(blank=True, max_length=25, null=True)),
                ('Dl_Number', models.CharField(blank=True, max_length=25, null=True)),
                ('Dl_State', models.CharField(blank=True, max_length=2, null=True)),
                ('Dl_Class', models.CharField(blank=True, max_length=2, null=True)),
                ('CDL_Presented_At_Scene', models.IntegerField(blank=True, null=True)),
                ('Transported_To', models.CharField(blank=True, max_length=2, null=True)),
                ('Injury_Level', models.CharField(blank=True, max_length=2, null=True)),
                ('Charge', models.CharField(blank=True, max_length=64, null=True)),
                ('Status_Code', models.CharField(blank=True, max_length=2, null=True)),
                ('Person_Type', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Vehicle_Number', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(88)])),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now, null=True)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='SignUp',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('email', models.EmailField(max_length=254)),
                ('full_name', models.CharField(blank=True, default='', max_length=50, null=True)),
                ('timestamp', models.DateTimeField(auto_now_add=True)),
                ('updated', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='uc',
            fields=[
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('FK', models.BigIntegerField(blank=True, null=True)),
                ('PS_case', models.BigIntegerField(blank=True, null=True)),
                ('PS_Case_ID', models.CharField(max_length=20, null=True)),
                ('DLD_Year', models.CharField(blank=True, max_length=4, null=True)),
                ('DLD', models.CharField(blank=True, max_length=20, null=True)),
                ('Date_of_Crash', models.DateField(blank=True, null=True)),
                ('County_Code', models.CharField(blank=True, max_length=3, null=True)),
                ('Route', models.CharField(blank=True, max_length=4, null=True)),
                ('Manner_Collision', models.CharField(blank=True, max_length=2, null=True)),
                ('Roadway_Contrib_Circum', models.CharField(blank=True, max_length=2, null=True)),
                ('Weather_Condition', models.CharField(blank=True, max_length=2, null=True)),
                ('First_Harmful_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Narrative', models.TextField(blank=True, null=True)),
                ('Total_Fatalities', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Assigned_Crash_Record', models.NullBooleanField(default=False)),
                ('QC_Comments', models.TextField(blank=True, null=True)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='up',
            fields=[
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('PS_case', models.BigIntegerField(blank=True, null=True)),
                ('FK', models.BigIntegerField(blank=True, null=True)),
                ('Prop', models.BigIntegerField(blank=True, null=True)),
                ('Vehicle_Number', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(88)])),
                ('Person_Type', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Safety_Equip', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('State_Reside', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(3)])),
                ('Sex', models.CharField(blank=True, max_length=3, null=True)),
                ('Full_Name', models.CharField(blank=True, max_length=75, null=True)),
                ('Age', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(125)])),
            ],
        ),
        migrations.CreateModel(
            name='uv',
            fields=[
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('PS_case', models.BigIntegerField(blank=True, null=True)),
                ('FK', models.BigIntegerField(blank=True, null=True)),
                ('Prop', models.BigIntegerField(blank=True, null=True)),
                ('Vehicle_Number', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(88)])),
                ('MV_Body', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MaxValueValidator(88)])),
            ],
        ),
        migrations.CreateModel(
            name='Vehicle',
            fields=[
                ('ID', models.AutoField(primary_key=True, serialize=False)),
                ('PS_case', models.BigIntegerField()),
                ('Vehicle_Number', models.IntegerField(null=True)),
                ('Vin_Verified', models.CharField(blank=True, max_length=2, null=True)),
                ('Vin', models.CharField(blank=True, max_length=40, null=True)),
                ('License_Plate_Number', models.CharField(blank=True, max_length=15, null=True)),
                ('License_Plate_State', models.CharField(blank=True, max_length=20, null=True)),
                ('Motor_Vehicle_Body_Type', models.CharField(blank=True, max_length=2, null=True)),
                ('Trailing_Units', models.CharField(blank=True, max_length=2, null=True)),
                ('Cargo_Body_Type', models.CharField(blank=True, max_length=2, null=True)),
                ('Special_Function_Code', models.CharField(blank=True, max_length=2, null=True)),
                ('First_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Second_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Third_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Fourth_Event', models.CharField(blank=True, max_length=2, null=True)),
                ('Roadway_Description', models.CharField(blank=True, max_length=2, null=True)),
                ('Disposition_Of_Vehicle', models.CharField(blank=True, max_length=20, null=True)),
                ('Towed_By', models.CharField(blank=True, max_length=25, null=True)),
                ('Carrier_Name', models.CharField(blank=True, max_length=64, null=True)),
                ('US_DOT_Number', models.CharField(blank=True, max_length=15, null=True)),
                ('US_DOT_Verified', models.CharField(blank=True, max_length=1, null=True)),
                ('GCWR_GVWR', models.CharField(blank=True, max_length=2, null=True)),
                ('Carrier_Address_Street', models.CharField(blank=True, max_length=40, null=True)),
                ('Carrier_Address_Street2', models.CharField(blank=True, max_length=40, null=True)),
                ('Carrier_Address_City', models.CharField(blank=True, max_length=25, null=True)),
                ('Carrier_Address_State', models.CharField(blank=True, max_length=2, null=True)),
                ('Carrier_Address_Zip', models.CharField(blank=True, max_length=12, null=True)),
                ('Carrier_Address_County', models.CharField(blank=True, max_length=3, null=True)),
                ('Carrier_Address_Phone', models.CharField(blank=True, max_length=25, null=True)),
                ('Is_Driver_Carrier', models.CharField(blank=True, max_length=1, null=True)),
                ('Interstate', models.CharField(blank=True, max_length=1, null=True)),
                ('Cargo_Code', models.CharField(blank=True, max_length=2, null=True)),
                ('Hazmat_Released', models.CharField(blank=True, max_length=1, null=True)),
                ('Hazmat_Placard_Number', models.CharField(blank=True, max_length=20, null=True)),
                ('Is_Owner_Driver', models.CharField(blank=True, max_length=1, null=True)),
                ('Owner_First', models.CharField(blank=True, max_length=20, null=True)),
                ('Owner_Middle', models.CharField(blank=True, max_length=20, null=True)),
                ('Owner_Last', models.CharField(blank=True, max_length=20, null=True)),
                ('Owner_Address_Street', models.CharField(blank=True, max_length=40, null=True)),
                ('Owner_Address_Street2', models.CharField(blank=True, max_length=40, null=True)),
                ('Owner_Address_City', models.CharField(blank=True, max_length=25, null=True)),
                ('Owner_Address_State', models.CharField(blank=True, max_length=2, null=True)),
                ('Owner_Address_Zip', models.CharField(blank=True, max_length=12, null=True)),
                ('Owner_Phone', models.CharField(blank=True, max_length=25, null=True)),
                ('Vehicle_ID', models.IntegerField(blank=True, null=True)),
                ('Make', models.CharField(blank=True, max_length=15, null=True)),
                ('Vehicle_Model', models.CharField(blank=True, max_length=15, null=True)),
                ('Travel_Direction', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Vehicle_Maneuver', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Traffic_Control_Device', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('Driver_Condition', models.IntegerField(null=True, validators=[django.core.validators.MaxValueValidator(99)])),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now, null=True)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
            ],
        ),
    ]
Esempio n. 9
0
class Ip(models.Model):
    """An :class:`Ip` instance represents either an IPv4 or IPv6 address.

    :class:`Ip` instances are used in the :ref:`address_record` (A and AAAA
    records), :ref:`ptr`, and the :ref:`staticinterface` classes.

    :class:`Ip` instances in a :ref:`ptr` record must be mapped back to a
    Reverse :ref:`domain` object. A :class:`ValidationError` is raised if an
    eligible Reverse :ref:`domain` cannot be found when trying to create the
    :ref:`ptr`'s :class:`Ip`.

    The reason why an IP must be mapped back to a Reverse :ref:`domain` has to
    do with how bind files are generated. In a reverse zone file, ip addresses
    are mapped from IP to DATA. For instance an :ref:`ptr` record would
    look like this::

        IP                  DATA
        197.1.1.1   PTR     foo.bob.com

    If we were building the file ``197.in-addr.arpa``, all IP addresses
    in the ``197`` domain would need to be in this file. To reduce the
    complexity of finding records for a reverse domain, an :class:`IP` is
    linked to it's appropriate reverse domain when it is created. It's
    mapping is updated when it's reverse domain is deleted or a more
    appropritate reverse domain is added.  Keeping the :class:`Ip` feild on
    :ref:`ptr` will help preformance when building reverse zone files.

    The algorithm for determineing which reverse domain an :class:`Ip`
    belongs to is done by applying a 'longest prefix match' to all
    reverse domains in the :ref:`domain` table.

    :ref:`address_record` objects need the ip validation that happens in this class
    but do not need their :class:`Ip`'s to be tied back to a reverse domain.

    :ref:`staticinterface` objects need to have their ip tied back to reverse
    domain because they represent a :ref:`PTR` record as well as an
    :ref:`address_record`.

    .. note::
        Django's BigInteger wasn't "Big" enough, so there is code
        in `cydns/ip/sql/ip.sql` that Alters the IP table.

    .. note::
        This class is abstract.

    """
    IP_TYPE_CHOICES = (('4', 'ipv4'), ('6', 'ipv6'))
    ip_str = models.CharField(max_length=39, editable=True, verbose_name='IP',
                              help_text="IP Address in IPv4 or IPv6 Format")
    # ip_upper/lower are calculated from ip_str on ip_clean.
    # TODO rename ip_* to ipaddr_*
    ip_upper = models.BigIntegerField(null=True, blank=True)
    ip_lower = models.BigIntegerField(null=True, blank=True)
    # TODO, should reverse_domain go into the PTR model?  I would think
    # it shouldn't because it is used in this class during the ip_clean
    # function.  Technically the ip_clean function would work if the
    # field existed in the PTR model, but overall it would hurt
    # readability.
    #
    # reactor.addCallback(think_about_it)
    # This can't be factored out because the related name classes. i.e.:
    # address_record.addressrecord: Accessor for field 'domain' clashes with
    # related field 'Domain.addressrecord_set'. Add a related_name argument to
    # the definition for 'domain'.
    # reverse_domain = models.ForeignKey(Domain, null=True, blank=True)
    ip_type = models.CharField(max_length=1, choices=IP_TYPE_CHOICES,
                               editable=True, help_text='IPv4 or IPv6 Address type')

    class Meta:
        abstract = True

    def clean_ip(self, update_reverse_domain=True):
        """
        The clean method in Ip is different from the rest. It needs
        to be called with the update_reverse_domain flag. Sometimes we
        need to not update the reverse domain of an IP (i.e. when we are
        deleting a reverse_domain).
        """
        # TODO, it's a f*****g hack. Car babies.
        validate_ip_type(self.ip_type)
        self._validate_ip_str()
        if self.ip_type == '4':
            try:
                ip = ipaddr.IPv4Address(self.ip_str)
                self.ip_str = str(ip)
            except ipaddr.AddressValueError, e:
                raise ValidationError("Invalid Ip address {0}".
                                      format(self.ip_str))

            if update_reverse_domain:
                # Resolve IP to domain name.
                no_match = False
                try:
                    self.reverse_domain = (name_to_domain(
                                           ip_to_domain_name(self.ip_str,
                                                             ip_type='4')))
                except ValueError:
                    no_match = True

                if (no_match or self.reverse_domain is None or
                    self.reverse_domain.name in ('arpa', 'in-addr.arpa',
                                                 'ipv6.arpa')):
                    raise ValidationError("No reverse Domain found for {0} "
                                          .format(self.ip_str))
            self.ip_upper = 0
            self.ip_lower = int(ip)
        else:
Esempio n. 10
0
class Migration(migrations.Migration):

    dependencies = [
        ('app', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='AuthGroup',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=150, unique=True)),
            ],
            options={
                'db_table': 'auth_group',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='AuthGroupPermissions',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
            ],
            options={
                'db_table': 'auth_group_permissions',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='AuthPermission',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('codename', models.CharField(max_length=100)),
            ],
            options={
                'db_table': 'auth_permission',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='AuthUser',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('password', models.CharField(max_length=128)),
                ('last_login', models.DateTimeField(blank=True, null=True)),
                ('is_superuser', models.IntegerField()),
                ('username', models.CharField(max_length=150, unique=True)),
                ('first_name', models.CharField(max_length=30)),
                ('last_name', models.CharField(max_length=150)),
                ('email', models.CharField(max_length=254)),
                ('is_staff', models.IntegerField()),
                ('is_active', models.IntegerField()),
                ('date_joined', models.DateTimeField()),
            ],
            options={
                'db_table': 'auth_user',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='AuthUserGroups',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
            ],
            options={
                'db_table': 'auth_user_groups',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='AuthUserUserPermissions',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
            ],
            options={
                'db_table': 'auth_user_user_permissions',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Books',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('bookid',
                 models.CharField(blank=True, max_length=20, null=True)),
                ('bookname',
                 models.CharField(blank=True, max_length=20, null=True)),
            ],
            options={
                'db_table': 'books',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='Coca',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('rank',
                 models.TextField(blank=True, db_column='RANK', null=True)),
                ('pos', models.TextField(blank=True,
                                         db_column='PoS',
                                         null=True)),
                ('word', models.TextField(blank=True, null=True)),
                ('total',
                 models.BigIntegerField(blank=True,
                                        db_column='TOTAL',
                                        null=True)),
                ('spoken',
                 models.IntegerField(blank=True, db_column='SPOKEN',
                                     null=True)),
                ('fiction',
                 models.BigIntegerField(blank=True,
                                        db_column='FICTION',
                                        null=True)),
                ('magazine',
                 models.BigIntegerField(blank=True,
                                        db_column='MAGAZINE',
                                        null=True)),
                ('newspaper',
                 models.IntegerField(blank=True,
                                     db_column='NEWSPAPER',
                                     null=True)),
                ('academic',
                 models.IntegerField(blank=True,
                                     db_column='ACADEMIC',
                                     null=True)),
            ],
            options={
                'db_table': 'coca',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='DjangoAdminLog',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('action_time', models.DateTimeField()),
                ('object_id', models.TextField(blank=True, null=True)),
                ('object_repr', models.CharField(max_length=200)),
                ('action_flag', models.PositiveSmallIntegerField()),
                ('change_message', models.TextField()),
            ],
            options={
                'db_table': 'django_admin_log',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='DjangoContentType',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('app_label', models.CharField(max_length=100)),
                ('model', models.CharField(max_length=100)),
            ],
            options={
                'db_table': 'django_content_type',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='DjangoMigrations',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('app', models.CharField(max_length=255)),
                ('name', models.CharField(max_length=255)),
                ('applied', models.DateTimeField()),
            ],
            options={
                'db_table': 'django_migrations',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='DjangoSession',
            fields=[
                ('session_key',
                 models.CharField(max_length=40,
                                  primary_key=True,
                                  serialize=False)),
                ('session_data', models.TextField()),
                ('expire_date', models.DateTimeField()),
            ],
            options={
                'db_table': 'django_session',
                'managed': False,
            },
        ),
        migrations.CreateModel(
            name='UserWordsInfomation',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('user_id',
                 models.CharField(blank=True, max_length=45, null=True)),
                ('book_id',
                 models.CharField(blank=True, max_length=45, null=True)),
                ('word', models.TextField(blank=True, null=True)),
                ('learn_time',
                 models.CharField(blank=True, max_length=40, null=True)),
                ('review_time', models.TextField(blank=True, null=True)),
                ('unknown_time', models.TextField(blank=True, null=True)),
            ],
            options={
                'db_table': 'user_words_infomation',
                'managed': False,
            },
        ),
    ]
Esempio n. 11
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Industry',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
            ],
        ),
        migrations.CreateModel(
            name='Listing',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('date', models.DateTimeField()),
                ('opening', models.DecimalField(decimal_places=5,
                                                max_digits=11)),
                ('high', models.DecimalField(decimal_places=5, max_digits=11)),
                ('low', models.DecimalField(decimal_places=5, max_digits=11)),
                ('closing', models.DecimalField(decimal_places=5,
                                                max_digits=11)),
                ('wap', models.DecimalField(decimal_places=11, max_digits=20)),
                ('traded', models.BigIntegerField()),
                ('trades', models.BigIntegerField()),
                ('turnover', models.BigIntegerField()),
                ('deliverable', models.BigIntegerField()),
                ('ratio', models.DecimalField(decimal_places=2,
                                              max_digits=10)),
                ('spread_high_low',
                 models.DecimalField(decimal_places=10, max_digits=20)),
                ('spread_close_open',
                 models.DecimalField(decimal_places=10, max_digits=20)),
            ],
        ),
        migrations.CreateModel(
            name='Stock',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('security', models.BigIntegerField()),
                ('sid', models.CharField(max_length=15)),
                ('name', models.CharField(max_length=255)),
                ('group', models.CharField(blank=True,
                                           default='',
                                           max_length=5)),
                ('face_value',
                 models.DecimalField(decimal_places=4, max_digits=10)),
                ('isin', models.CharField(max_length=15)),
                ('industry',
                 models.ForeignKey(
                     default=None,
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     to='stocks.Industry')),
            ],
        ),
        migrations.AddField(
            model_name='listing',
            name='stock',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='stocks.Stock'),
        ),
    ]
Esempio n. 12
0
class Artifact(HandleTempFilesMixin, BaseModel):
    """
    A file associated with a piece of content.

    When calling `save()` on an Artifact, if the file is not stored in Django's storage backend, it
    is moved into place then.

    Artifact is compatible with Django's `bulk_create()` method.

    Fields:

        file (pulpcore.app.models.fields.ArtifactFileField): The stored file. This field should
            be set using an absolute path to a temporary file.
            It also accepts `class:django.core.files.File`.
        size (models.BigIntegerField): The size of the file in bytes.
        md5 (models.CharField): The MD5 checksum of the file.
        sha1 (models.CharField): The SHA-1 checksum of the file.
        sha224 (models.CharField): The SHA-224 checksum of the file.
        sha256 (models.CharField): The SHA-256 checksum of the file (REQUIRED).
        sha384 (models.CharField): The SHA-384 checksum of the file.
        sha512 (models.CharField): The SHA-512 checksum of the file.
    """
    def storage_path(self, name):
        """
        Callable used by FileField to determine where the uploaded file should be stored.

        Args:
            name (str): Original name of uploaded file. It is ignored by this method because the
                sha256 checksum is used to determine a file path instead.
        """
        return storage.get_artifact_path(self.sha256)

    file = fields.ArtifactFileField(null=False,
                                    upload_to=storage_path,
                                    max_length=255)
    size = models.BigIntegerField(null=False)
    md5 = models.CharField(max_length=32,
                           null=True,
                           unique=False,
                           db_index=True)
    sha1 = models.CharField(max_length=40,
                            null=True,
                            unique=False,
                            db_index=True)
    sha224 = models.CharField(max_length=56,
                              null=True,
                              unique=False,
                              db_index=True)
    sha256 = models.CharField(max_length=64,
                              null=False,
                              unique=True,
                              db_index=True)
    sha384 = models.CharField(max_length=96,
                              null=True,
                              unique=True,
                              db_index=True)
    sha512 = models.CharField(max_length=128,
                              null=True,
                              unique=True,
                              db_index=True)

    objects = BulkCreateManager()

    # All available digest fields ordered by algorithm strength.
    DIGEST_FIELDS = _DIGEST_FIELDS

    # All available digest fields ordered by relative frequency
    # (Better average-case performance in some algorithms with fallback)
    COMMON_DIGEST_FIELDS = _COMMON_DIGEST_FIELDS

    # Available, reliable digest fields ordered by algorithm strength.
    RELIABLE_DIGEST_FIELDS = _RELIABLE_DIGEST_FIELDS

    # Digest-fields that are NOT ALLOWED
    FORBIDDEN_DIGESTS = _FORBIDDEN_DIGESTS

    def __init__(self, *args, **kwargs):
        """
        Initialization override to reject use of disallowed checksum algorithms.

        Args:
            args: positional arguments
            kwargs: keyword arguments

        Raises:
            :class: `~pulpcore.exceptions.UnsupportedDigestValidationError`: When any of the
                keys in kwargs are found on the FORBIDDEN_DIGESTS list
        """
        bad_keys = self.FORBIDDEN_DIGESTS.intersection(kwargs.keys())
        if bad_keys:
            raise UnsupportedDigestValidationError(
                _(f"Checksum algorithms {bad_keys} are forbidden for this Pulp instance."
                  ))
        super().__init__(*args, **kwargs)

    def q(self):
        if not self._state.adding:
            return models.Q(pk=self.pk)
        for digest_name in self.DIGEST_FIELDS:
            digest_value = getattr(self, digest_name)
            if digest_value:
                return models.Q(**{digest_name: digest_value})
        return models.Q()

    def is_equal(self, other):
        """
        Is equal by matching digest.

        Args:
            other (pulpcore.app.models.Artifact): A artifact to match.

        Returns:
            bool: True when equal.
        """
        for field in self.RELIABLE_DIGEST_FIELDS:
            digest = getattr(self, field)
            if not digest:
                continue
            if digest == getattr(other, field):
                return True
        return False

    @staticmethod
    def init_and_validate(file, expected_digests=None, expected_size=None):
        """
        Initialize an in-memory Artifact from a file, and validate digest and size info.

        This accepts both a path to a file on-disk or a
        :class:`~pulpcore.app.files.PulpTemporaryUploadedFile`.

        Args:
            file (:class:`~pulpcore.app.files.PulpTemporaryUploadedFile` or str): The
                PulpTemporaryUploadedFile to create the Artifact from or a string with the full path
                to the file on disk.
            expected_digests (dict): Keyed on the algorithm name provided by hashlib and stores the
                value of the expected digest. e.g. {'md5': '912ec803b2ce49e4a541068d495ab570'}
            expected_size (int): The number of bytes the download is expected to have.

        Raises:
            :class:`~pulpcore.exceptions.DigestValidationError`: When any of the ``expected_digest``
                values don't match the digest of the data
            :class:`~pulpcore.exceptions.SizeValidationError`: When the ``expected_size`` value
                doesn't match the size of the data
            :class:`~pulpcore.exceptions.UnsupportedDigestValidationError`: When any of the
                ``expected_digest`` algorithms aren't in the ALLOWED_CONTENT_CHECKSUMS list
        Returns:
            An in-memory, unsaved :class:`~pulpcore.plugin.models.Artifact`
        """
        if isinstance(file, str):
            with open(file, "rb") as f:
                hashers = {n: hashlib.new(n) for n in Artifact.DIGEST_FIELDS}
                size = 0
                while True:
                    chunk = f.read(1048576)  # 1 megabyte
                    if not chunk:
                        break
                    for algorithm in hashers.values():
                        algorithm.update(chunk)
                    size = size + len(chunk)
        else:
            size = file.size
            hashers = file.hashers

        if expected_size:
            if size != expected_size:
                raise SizeValidationError()

        if expected_digests:
            for algorithm, expected_digest in expected_digests.items():
                if algorithm not in hashers:
                    raise UnsupportedDigestValidationError(
                        _(f"Checksum algorithm {algorithm} forbidden for this Pulp instance."
                          ))
                if expected_digest != hashers[algorithm].hexdigest():
                    raise DigestValidationError()

        attributes = {"size": size, "file": file}
        for algorithm in Artifact.DIGEST_FIELDS:
            attributes[algorithm] = hashers[algorithm].hexdigest()

        return Artifact(**attributes)

    @classmethod
    def from_pulp_temporary_file(cls, temp_file):
        """
        Creates an Artifact from PulpTemporaryFile.

        Returns:
            An saved :class:`~pulpcore.plugin.models.Artifact`
        """
        artifact_file = default_storage.open(temp_file.file.name)
        with tempfile.NamedTemporaryFile("wb") as new_file:
            shutil.copyfileobj(artifact_file, new_file)
            new_file.flush()
            artifact = cls.init_and_validate(new_file.name)
            artifact.save()
        temp_file.delete()
        return artifact
Esempio n. 13
0
class Customer(models.Model):
    """
    客户表
    """
    qq = models.CharField('QQ',
                          max_length=64,
                          unique=True,
                          help_text='QQ号必须唯一')
    qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True)
    name = models.CharField('姓名',
                            max_length=32,
                            blank=True,
                            null=True,
                            help_text='学员报名后,请改为真实姓名')
    sex_type = (('male', '男'), ('female', '女'))
    sex = models.CharField("性别",
                           choices=sex_type,
                           max_length=16,
                           default='male',
                           blank=True,
                           null=True)
    birthday = models.DateField('出生日期',
                                default=None,
                                help_text="格式yyyy-mm-dd",
                                blank=True,
                                null=True)
    phone = models.BigIntegerField('手机号', blank=True, null=True)
    source = models.CharField('客户来源',
                              max_length=64,
                              choices=source_type,
                              default='qq')
    introduce_from = models.ForeignKey('self',
                                       verbose_name="转介绍自学员",
                                       blank=True,
                                       null=True)
    course = MultiSelectField("咨询课程", choices=course_choices)
    class_type = models.CharField("班级类型",
                                  max_length=64,
                                  choices=class_type_choices,
                                  default='fulltime')
    customer_note = models.TextField(
        "客户备注",
        blank=True,
        null=True,
    )
    status = models.CharField("状态",
                              choices=enroll_status_choices,
                              max_length=64,
                              default="unregistered",
                              help_text="选择客户此时的状态")
    last_consult_date = models.DateField("最后跟进日期", auto_now_add=True)
    next_date = models.DateField("预计再次跟进时间", blank=True, null=True)
    consultant = models.ForeignKey(
        'UserProfile',
        verbose_name="销售",
        related_name='customers',
        blank=True,
        null=True,
    )
    class_list = models.ManyToManyField('ClassList',
                                        verbose_name="已报班级",
                                        blank=True)

    # 将客户对象显示为对应内容
    def __str__(self):
        return "{}-{}".format(self.name, self.qq)

    # 展示客户已报班级
    def show_class(self):
        return ' | '.join([str(i) for i in self.class_list.all()])

    # 根据状态不同在前端显示不同的颜色
    def show_status_with_color(self):
        """
             (('signed', "已报名"),
             ('unregistered', "未报名"),
             ('studying', '学习中'),
             ('paid_in_full', "学费已交齐"))
            :return:
        """
        status_color = {
            'signed': '#CED643',  # 黄色
            'unregistered': '#D9534F',  # 红色
            'studying': '#5CB85C',  # 绿色
            'paid_in_full': '#2F72AB'  # 蓝色
        }
        return mark_safe(
            '<p style="background-color:{}; color:#FFF;" class="btn center" type="button">{}</p>'
            .format(status_color.get(self.status), self.get_status_display()))
Esempio n. 14
0
class ImageOcr(BasicModel, BIDModel):
    """ 图片OCR识别记录 """
    class Meta:
        verbose_name = 'ImageOcr'
        verbose_name_plural = verbose_name
        index_together = ['ocr_type', 'suggestion', 'is_victor']
        db_table = 'k_os_image_ocr'
        ordering = ('-pk', )

    oss_key = models.URLField('图片路径', unique=True)
    usrid = models.BigIntegerField('用户', db_index=True, default=0)
    rate = models.DecimalField('置信度',
                               max_digits=5,
                               decimal_places=2,
                               default=0)
    ocr_type = models.PositiveSmallIntegerField('OCR类型',
                                                choices=mc.OCRType.choices,
                                                default=0)
    suggestion = models.CharField('建议操作',
                                  choices=mc.Suggestion.choices,
                                  max_length=20,
                                  default='')
    ocr_use_ms = models.PositiveSmallIntegerField('OCR耗时', default=0)
    reason = models.CharField('原因', max_length=200, default='')
    is_victor = models.BooleanField('是否成功', null=True, default=None)
    result = models.JSONField('结果', default=dict)  # 加密

    objects = ImageOcrManager()

    @property
    def oss_url(self):
        """ OSS URL,无水印,60秒内有效 """
        url = oss_sign_url(self.oss_key)
        return url

    @property
    def result_dic(self):
        """ 结果解密 """
        dic = decrypt_dic(self.result)
        return dic

    def do_ocr_query(self):
        if self.is_victor:
            logger.info(f'do_ocr_query__is_victor {self.pk}')
            return
        ts_start = int(1000 * time.time())
        result = ocr_query(self.oss_url, str(self.pk), self.ocr_type)
        self.ocr_use_ms = int(1000 * time.time()) - ts_start
        up_fields = ['is_victor', 'ocr_use_ms', 'updated_at']
        if not isinstance(result, dict):
            self.is_victor = False
            self.reason = str(result)
            up_fields.append('reason')
            self.save(update_fields=up_fields)
            logger.warning(f'do_ocr_query__fail {self.pk} {str(result)}')
            return
        self.is_victor = True
        self.rate = result['_rate']
        self.result = encrypt_dic(result)
        self.suggestion = result['_suggestion']
        up_fields.extend(['rate', 'result', 'suggestion'])
        self.save(update_fields=up_fields)
Esempio n. 15
0
class MonsterInstance(models.Model, base.Stars):
    PRIORITY_DONE = 0
    PRIORITY_LOW = 1
    PRIORITY_MED = 2
    PRIORITY_HIGH = 3

    PRIORITY_CHOICES = [
        (PRIORITY_LOW, 'Low'),
        (PRIORITY_MED, 'Medium'),
        (PRIORITY_HIGH, 'High'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    owner = models.ForeignKey(Summoner, on_delete=models.CASCADE)
    monster = models.ForeignKey(Monster, on_delete=models.CASCADE)
    com2us_id = models.BigIntegerField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True)
    stars = models.IntegerField(choices=base.Stars.STAR_CHOICES)
    level = models.IntegerField()
    skill_1_level = models.IntegerField(blank=True, default=1)
    skill_2_level = models.IntegerField(blank=True, default=1)
    skill_3_level = models.IntegerField(blank=True, default=1)
    skill_4_level = models.IntegerField(blank=True, default=1)
    fodder = models.BooleanField(default=False)
    in_storage = models.BooleanField(default=False)
    ignore_for_fusion = models.BooleanField(default=False)
    priority = models.IntegerField(choices=PRIORITY_CHOICES,
                                   blank=True,
                                   null=True)
    tags = models.ManyToManyField(MonsterTag, blank=True)
    notes = models.TextField(
        null=True,
        blank=True,
        help_text=mark_safe(
            '<a href="https://daringfireball.net/projects/markdown/syntax" target="_blank">Markdown syntax</a> enabled'
        ))
    custom_name = models.CharField(default='', max_length=20, blank=True)
    default_build = models.ForeignKey('RuneBuild',
                                      null=True,
                                      on_delete=models.SET_NULL,
                                      related_name='default_build')
    rta_build = models.ForeignKey('RuneBuild',
                                  null=True,
                                  on_delete=models.SET_NULL,
                                  related_name='rta_build')

    # Calculated fields (on save)
    rune_hp = models.IntegerField(blank=True, default=0)
    rune_attack = models.IntegerField(blank=True, default=0)
    rune_defense = models.IntegerField(blank=True, default=0)
    rune_speed = models.IntegerField(blank=True, default=0)
    rune_crit_rate = models.IntegerField(blank=True, default=0)
    rune_crit_damage = models.IntegerField(blank=True, default=0)
    rune_resistance = models.IntegerField(blank=True, default=0)
    rune_accuracy = models.IntegerField(blank=True, default=0)
    avg_rune_efficiency = models.FloatField(blank=True, null=True)

    class Meta:
        ordering = ['-stars', '-level', 'monster__name']

    def __str__(self):
        return f'{self.get_stars_display()} {self.monster} Lv. {self.level}'

    def is_max_level(self):
        return self.level == self.monster.max_level_from_stars(self.stars)

    def max_level_from_stars(self):
        return self.monster.max_level_from_stars(self.stars)

    def skill_ups_to_max(self):
        skill_ups_remaining = self.monster.skill_ups_to_max or 0
        skill_levels = [
            self.skill_1_level, self.skill_2_level, self.skill_3_level,
            self.skill_4_level
        ]

        for idx in range(0, self.monster.skills.count()):
            skill_ups_remaining -= skill_levels[idx] - 1

        return skill_ups_remaining

    def get_rune_set_summary(self):
        sets = []

        # Determine rune sets
        rune_counts = self.runeinstance_set.values('type').order_by().annotate(
            count=Count('type'))
        num_equipped = self.runeinstance_set.count()

        for rune_count in rune_counts:
            type_name = RuneInstance.TYPE_CHOICES[rune_count['type'] - 1][1]
            required = RuneInstance.RUNE_SET_COUNT_REQUIREMENTS[
                rune_count['type']]
            present = rune_count['count']

            if present >= required:
                num_equipped -= required * (present // required)
                sets += [type_name] * (present // required)

        if num_equipped:
            # Some runes are present that aren't in a set
            sets.append('Broken')

        # Summarize slot 2/4/6 main stats
        stats = []

        for x in [2, 4, 6]:
            try:
                stats.append(
                    self.runeinstance_set.get(slot=x).get_main_stat_display())
            except:
                continue

        return '/'.join(sets) + ' - ' + '/'.join(stats)

    def get_rune_set_bonuses(self):
        rune_counts = self.runeinstance_set.values('type').order_by().annotate(
            count=Count('type'))
        rune_bonuses = []

        for rune_count in rune_counts:
            required = RuneInstance.RUNE_SET_COUNT_REQUIREMENTS[
                rune_count['type']]
            present = rune_count['count']
            bonus_text = RuneInstance.RUNE_SET_BONUSES[
                rune_count['type']]['description']

            if present >= required:
                rune_bonuses.extend([bonus_text] * (present // required))

        return rune_bonuses

    def get_avg_rune_efficiency(self):
        # TODO: Switch after switching to rune builds
        # return self.default_build.avg_efficiency
        return self.runeinstance_set.aggregate(
            Avg('efficiency'))['efficiency__avg'] or 0.0

    # Stat values for current monster grade/level
    @cached_property
    def base_stats(self):
        return self.monster.get_stats(self.stars, self.level)

    @cached_property
    def max_base_stats(self):
        return self.monster.get_stats(6, 40)

    @property
    def base_hp(self):
        return self.base_stats[base.Stats.STAT_HP]

    @property
    def base_attack(self):
        return self.base_stats[base.Stats.STAT_ATK]

    @property
    def base_defense(self):
        return self.base_stats[base.Stats.STAT_DEF]

    @property
    def base_speed(self):
        return self.base_stats[base.Stats.STAT_SPD]

    @property
    def base_crit_rate(self):
        return self.base_stats[base.Stats.STAT_CRIT_RATE_PCT]

    @property
    def base_crit_damage(self):
        return self.base_stats[base.Stats.STAT_CRIT_DMG_PCT]

    @property
    def base_resistance(self):
        return self.base_stats[base.Stats.STAT_RESIST_PCT]

    @property
    def base_accuracy(self):
        return self.base_stats[base.Stats.STAT_ACCURACY_PCT]

    # Stat bonuses from default rune set
    # TODO: Use this code after switching to rune builds
    # @cached_property
    # def rune_stats(self):
    #     val = self._calc_rune_stats(self.base_stats.copy())
    #     return val
    #
    # @cached_property
    # def max_rune_stats(self):
    #     return self._calc_rune_stats(self.max_base_stats.copy())
    #
    # def _calc_rune_stats(self, base_stats):
    #     rune_stats = self.default_build.rune_stats.copy()
    #
    #     # Convert HP/ATK/DEF percentage bonuses to flat bonuses based on the base stats
    #     for stat, converts_to in base.Stats.CONVERTS_TO_FLAT_STAT.items():
    #         rune_stats[converts_to] += int(ceil(round(base_stats.get(converts_to, 0.0) * (rune_stats[stat] / 100.0), 3)))
    #         del rune_stats[stat]
    #
    #     return rune_stats
    #
    # @property
    # def rune_hp(self):
    #     val = self.rune_stats.get(base.Stats.STAT_HP, 0.0)
    #     return val
    #
    # @property
    # def rune_attack(self):
    #     return self.rune_stats.get(base.Stats.STAT_ATK, 0.0)
    #
    # @property
    # def rune_defense(self):
    #     return self.rune_stats.get(base.Stats.STAT_DEF, 0.0)
    #
    # @property
    # def rune_speed(self):
    #     return self.rune_stats.get(base.Stats.STAT_SPD, 0.0)
    #
    # @property
    # def rune_crit_rate(self):
    #     return self.rune_stats.get(base.Stats.STAT_CRIT_RATE_PCT, 0.0)
    #
    # @property
    # def rune_crit_damage(self):
    #     return self.rune_stats.get(base.Stats.STAT_CRIT_DMG_PCT, 0.0)
    #
    # @property
    # def rune_resistance(self):
    #     return self.rune_stats.get(base.Stats.STAT_RESIST_PCT, 0.0)
    #
    # @property
    # def rune_accuracy(self):
    #     return self.rune_stats.get(base.Stats.STAT_ACCURACY_PCT, 0.0)
    #
    # @property
    # def avg_rune_efficiency(self):
    #     return self.default_build.avg_efficiency

    # Totals for stats including rune bonuses
    def hp(self):
        return self.base_hp + self.rune_hp

    def attack(self):
        return self.base_attack + self.rune_attack

    def defense(self):
        return self.base_defense + self.rune_defense

    def speed(self):
        return self.base_speed + self.rune_speed

    def crit_rate(self):
        return self.base_crit_rate + self.rune_crit_rate

    def crit_damage(self):
        return self.base_crit_damage + self.rune_crit_damage

    def resistance(self):
        return self.base_resistance + self.rune_resistance

    def accuracy(self):
        return self.base_accuracy + self.rune_accuracy

    def get_rune_stats(self, at_max_level=False):
        # TODO: Delete after switching to rune builds
        if at_max_level:
            base_stats = {
                RuneInstance.STAT_HP: self.monster.actual_hp(6, 40),
                RuneInstance.STAT_HP_PCT: self.monster.actual_hp(6, 40),
                RuneInstance.STAT_ATK: self.monster.actual_attack(6, 40),
                RuneInstance.STAT_ATK_PCT: self.monster.actual_attack(6, 40),
                RuneInstance.STAT_DEF: self.monster.actual_defense(6, 40),
                RuneInstance.STAT_DEF_PCT: self.monster.actual_defense(6, 40),
                RuneInstance.STAT_SPD: self.base_speed,
                RuneInstance.STAT_CRIT_RATE_PCT: self.base_crit_rate,
                RuneInstance.STAT_CRIT_DMG_PCT: self.base_crit_damage,
                RuneInstance.STAT_RESIST_PCT: self.base_resistance,
                RuneInstance.STAT_ACCURACY_PCT: self.base_accuracy,
            }
        else:
            base_stats = {
                RuneInstance.STAT_HP: self.base_hp,
                RuneInstance.STAT_HP_PCT: self.base_hp,
                RuneInstance.STAT_ATK: self.base_attack,
                RuneInstance.STAT_ATK_PCT: self.base_attack,
                RuneInstance.STAT_DEF: self.base_defense,
                RuneInstance.STAT_DEF_PCT: self.base_defense,
                RuneInstance.STAT_SPD: self.base_speed,
                RuneInstance.STAT_CRIT_RATE_PCT: self.base_crit_rate,
                RuneInstance.STAT_CRIT_DMG_PCT: self.base_crit_damage,
                RuneInstance.STAT_RESIST_PCT: self.base_resistance,
                RuneInstance.STAT_ACCURACY_PCT: self.base_accuracy,
            }

        # Update stats based on runes
        rune_set = self.runeinstance_set.all()
        stat_bonuses = {stat_id: 0 for stat_id, _ in RuneInstance.STAT_CHOICES}
        rune_set_counts = {
            type_id: 0
            for type_id, _ in RuneInstance.TYPE_CHOICES
        }

        # Sum up all stat bonuses
        for rune in rune_set:
            rune_set_counts[rune.type] += 1
            stat_bonuses[RuneInstance.STAT_HP] += rune.get_stat(
                RuneInstance.STAT_HP)
            stat_bonuses[RuneInstance.STAT_HP_PCT] += rune.get_stat(
                RuneInstance.STAT_HP_PCT)
            stat_bonuses[RuneInstance.STAT_ATK] += rune.get_stat(
                RuneInstance.STAT_ATK)
            stat_bonuses[RuneInstance.STAT_ATK_PCT] += rune.get_stat(
                RuneInstance.STAT_ATK_PCT)
            stat_bonuses[RuneInstance.STAT_DEF] += rune.get_stat(
                RuneInstance.STAT_DEF)
            stat_bonuses[RuneInstance.STAT_DEF_PCT] += rune.get_stat(
                RuneInstance.STAT_DEF_PCT)
            stat_bonuses[RuneInstance.STAT_SPD] += rune.get_stat(
                RuneInstance.STAT_SPD)
            stat_bonuses[RuneInstance.STAT_CRIT_RATE_PCT] += rune.get_stat(
                RuneInstance.STAT_CRIT_RATE_PCT)
            stat_bonuses[RuneInstance.STAT_CRIT_DMG_PCT] += rune.get_stat(
                RuneInstance.STAT_CRIT_DMG_PCT)
            stat_bonuses[RuneInstance.STAT_RESIST_PCT] += rune.get_stat(
                RuneInstance.STAT_RESIST_PCT)
            stat_bonuses[RuneInstance.STAT_ACCURACY_PCT] += rune.get_stat(
                RuneInstance.STAT_ACCURACY_PCT)

        # Add in the set bonuses
        for set, count in rune_set_counts.items():
            required_count = RuneInstance.RUNE_SET_BONUSES[set]['count']
            bonus_value = RuneInstance.RUNE_SET_BONUSES[set]['value']
            if bonus_value is not None and count >= required_count:
                num_sets_equipped = floor(count / required_count)
                stat = RuneInstance.RUNE_SET_BONUSES[set]['stat']

                if set == RuneInstance.TYPE_SWIFT:
                    # Swift set is special because it adds a percentage to a normally flat stat
                    bonus_value = int(
                        ceil(
                            round(
                                base_stats[RuneInstance.STAT_SPD] *
                                (bonus_value / 100.0), 3)))
                    stat = RuneInstance.STAT_SPD

                stat_bonuses[stat] += bonus_value * num_sets_equipped

        # Convert HP/ATK/DEF percentage bonuses to flat bonuses based on the base stats
        for stat in [
                RuneInstance.STAT_HP_PCT, RuneInstance.STAT_ATK_PCT,
                RuneInstance.STAT_DEF_PCT
        ]:
            stat_bonuses[stat] = int(
                ceil(round(base_stats[stat] * (stat_bonuses[stat] / 100.0),
                           3)))

        return stat_bonuses

    def get_max_level_stats(self):
        max_base_hp = self.monster.actual_hp(6, 40)
        max_base_atk = self.monster.actual_attack(6, 40)
        max_base_def = self.monster.actual_defense(6, 40)

        max_rune_stats = self.get_rune_stats(at_max_level=True)

        stats = {
            'base': {
                'hp': max_base_hp,
                'attack': max_base_atk,
                'defense': max_base_def,
            },
            'rune': {
                'hp': max_rune_stats.get(RuneInstance.STAT_HP, 0),
                'attack': max_rune_stats.get(RuneInstance.STAT_ATK, 0),
                'defense': max_rune_stats.get(RuneInstance.STAT_DEF, 0),
            },
        }

        stats['deltas'] = {
            'hp':
            int(
                round(
                    float(stats['base']['hp'] + stats['rune']['hp']) /
                    self.hp() * 100 - 100)),
            'attack':
            int(
                round(
                    float(stats['base']['attack'] + stats['rune']['attack']) /
                    self.attack() * 100 - 100)),
            'defense':
            int(
                round(
                    float(stats['base']['defense'] +
                          stats['rune']['defense']) / self.defense() * 100 -
                    100)),
        }

        return stats

    def get_building_stats(self, area=Building.AREA_GENERAL):
        owned_bldgs = BuildingInstance.objects.filter(
            Q(building__element__isnull=True)
            | Q(building__element=self.monster.element),
            owner=self.owner,
            building__area=area,
        ).select_related('building')

        bonuses = {
            Building.STAT_HP: 0,
            Building.STAT_ATK: 0,
            Building.STAT_DEF: 0,
            Building.STAT_SPD: 0,
            Building.STAT_CRIT_RATE_PCT: 0,
            Building.STAT_CRIT_DMG_PCT: 0,
            Building.STAT_RESIST_PCT: 0,
            Building.STAT_ACCURACY_PCT: 0,
        }

        for b in owned_bldgs:
            if b.building.affected_stat in bonuses.keys() and b.level > 0:
                bonuses[b.building.affected_stat] += b.building.stat_bonus[
                    b.level - 1]

        return {
            'hp':
            int(
                ceil(
                    round(self.base_hp * (bonuses[Building.STAT_HP] / 100.0),
                          3))),
            'attack':
            int(
                ceil(
                    round(
                        self.base_attack *
                        (bonuses[Building.STAT_ATK] / 100.0), 3))),
            'defense':
            int(
                ceil(
                    round(
                        self.base_defense *
                        (bonuses[Building.STAT_DEF] / 100.0), 3))),
            'speed':
            int(
                ceil(
                    round(
                        self.base_speed * (bonuses[Building.STAT_SPD] / 100.0),
                        3))),
            'crit_rate':
            bonuses[Building.STAT_CRIT_RATE_PCT],
            'crit_damage':
            bonuses[Building.STAT_CRIT_DMG_PCT],
            'resistance':
            bonuses[Building.STAT_RESIST_PCT],
            'accuracy':
            bonuses[Building.STAT_ACCURACY_PCT],
        }

    def get_guild_stats(self):
        return self.get_building_stats(Building.AREA_GUILD)

    def get_possible_skillups(self):
        same_family = Q(monster__family_id=self.monster.family_id)

        # Handle a few special cases for skillups outside of own family
        # Vampire Lord
        if self.monster.family_id == 23000:
            same_family |= Q(monster__family_id=14700)

        # Fairy Queen
        if self.monster.family_id == 19100:
            same_family |= Q(monster__family_id=10100)

        devilmon = MonsterInstance.objects.filter(
            owner=self.owner, monster__name='Devilmon').count()
        family = MonsterInstance.objects.filter(
            owner=self.owner).filter(same_family).exclude(
                pk=self.pk).order_by('ignore_for_fusion')
        pieces = MonsterPiece.objects.filter(
            owner=self.owner, monster__family_id=self.monster.family_id)

        return {
            'devilmon': devilmon,
            'family': family,
            'pieces': pieces,
            'none': devilmon + family.count() + pieces.count() == 0,
        }

    def clean(self):
        from django.core.exceptions import ValidationError

        # Check skill levels
        if self.skill_1_level is None or self.skill_1_level < 1:
            self.skill_1_level = 1
        if self.skill_2_level is None or self.skill_2_level < 1:
            self.skill_2_level = 1
        if self.skill_3_level is None or self.skill_3_level < 1:
            self.skill_3_level = 1
        if self.skill_4_level is None or self.skill_4_level < 1:
            self.skill_4_level = 1

        if self.level > 40 or self.level < 1:
            raise ValidationError(
                'Level out of range (Valid range %(min)s-%(max)s)',
                params={
                    'min': 1,
                    'max': 40
                },
                code='invalid_level')

        if self.stars and (self.level > 10 + self.stars * 5):
            raise ValidationError(
                'Level exceeds max for given star rating (Max: %(value)s)',
                params={'value': 10 + self.stars * 5},
                code='invalid_level')

        min_stars = self.monster.base_monster.base_stars

        if self.stars and (self.stars > 6 or self.stars < min_stars):
            raise ValidationError(
                'Star rating out of range (%(min)s to %(max)s)',
                params={
                    'min': min_stars,
                    'max': 6
                },
                code='invalid_stars')

        super(MonsterInstance, self).clean()

    def save(self, *args, **kwargs):
        # Remove custom name if not a homunculus
        if not self.monster.homunculus:
            self.custom_name = ''

        # Update rune stats based on level
        stat_bonuses = self.get_rune_stats()

        # Add all the bonuses together to get final values.
        self.rune_hp = stat_bonuses[RuneInstance.STAT_HP] + stat_bonuses[
            RuneInstance.STAT_HP_PCT]
        self.rune_attack = stat_bonuses[RuneInstance.STAT_ATK] + stat_bonuses[
            RuneInstance.STAT_ATK_PCT]
        self.rune_defense = stat_bonuses[RuneInstance.STAT_DEF] + stat_bonuses[
            RuneInstance.STAT_DEF_PCT]
        self.rune_speed = stat_bonuses[RuneInstance.STAT_SPD]
        self.rune_crit_rate = stat_bonuses[RuneInstance.STAT_CRIT_RATE_PCT]
        self.rune_crit_damage = stat_bonuses[RuneInstance.STAT_CRIT_DMG_PCT]
        self.rune_resistance = stat_bonuses[RuneInstance.STAT_RESIST_PCT]
        self.rune_accuracy = stat_bonuses[RuneInstance.STAT_ACCURACY_PCT]

        self.avg_rune_efficiency = self.get_avg_rune_efficiency()

        # Limit skill levels to the max level of the skill
        skills = self.monster.skills.all()

        if len(skills) >= 1 and self.skill_1_level > skills[0].max_level:
            self.skill_1_level = skills[0].max_level

        if len(skills) >= 2 and self.skill_2_level > skills[1].max_level:
            self.skill_2_level = skills[1].max_level

        if len(skills) >= 3 and self.skill_3_level > skills[2].max_level:
            self.skill_3_level = skills[2].max_level

        if len(skills) >= 4 and self.skill_4_level > skills[3].max_level:
            self.skill_4_level = skills[3].max_level

        super(MonsterInstance, self).save(*args, **kwargs)

        if self.default_build is None or self.rta_build is None:
            self._initialize_rune_build()

    def _initialize_rune_build(self):
        # Create empty rune builds if none exists
        added = False
        if self.default_build is None:
            self.default_build = RuneBuild.objects.create(
                owner_id=self.owner.pk,
                monster_id=self.pk,
                name='Equipped Runes',
            )

        if self.rta_build is None:
            self.rta_build = RuneBuild.objects.create(
                owner_id=self.owner.pk,
                monster_id=self.pk,
                name='Real-Time Arena',
            )
            added = True

        if added:
            self.save()

        self.default_build.runes.set(self.runeinstance_set.all(), clear=True)
class Migration(migrations.Migration):

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

    operations = [
        migrations.CreateModel(
            name='Person',
            fields=[
                ('telegram_id', models.BigIntegerField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=20)),
                ('surname', models.CharField(max_length=20)),
                ('patronymic', models.CharField(max_length=20, blank=True, null=True)),
                ('station', models.CharField(max_length=50, blank=True, null=True, choices=[('Новоясеневская', 'Новоясеневская'), ('Кузнецкий мост', 'Кузнецкий мост'), ('Бунинская аллея', 'Бунинская аллея'), ('Парк Победы_ж', 'Парк Победы_ж'), ('Текстильщики', 'Текстильщики'), ('Медведково', 'Медведково'), ('Арбатская_с', 'Арбатская_с'), ('Лермонтовский проспект', 'Лермонтовский проспект'), ('Ленинский проспект', 'Ленинский проспект'), ('Пушкинская', 'Пушкинская'), ('Лесопарковая', 'Лесопарковая'), ('Охотный ряд', 'Охотный ряд'), ('Белорусская_з', 'Белорусская_з'), ('Ломоносовский проспект', 'Ломоносовский проспект'), ('Университет', 'Университет'), ('Чкаловская', 'Чкаловская'), ('Бульвар Рокоссовского', 'Бульвар Рокоссовского'), ('Новокосино', 'Новокосино'), ('Борисово', 'Борисово'), ('Орехово', 'Орехово'), ('Каширская_с', 'Каширская_с'), ('Китай-город_о', 'Китай-город_о'), ('Кутузовская', 'Кутузовская'), ('Багратионовская', 'Багратионовская'), ('Кантемировская', 'Кантемировская'), ('Цветной бульвар', 'Цветной бульвар'), ('Динамо', 'Динамо'), ('Румянцево', 'Румянцево'), ('Боровицкая', 'Боровицкая'), ('Улица 1905 года', 'Улица 1905 года'), ('Печатники', 'Печатники'), ('Черкизовская', 'Черкизовская'), ('Бульвар Дмитрия Донского', 'Бульвар Дмитрия Донского'), ('Мякинино', 'Мякинино'), ('Котельники', 'Котельники'), ('Спортивная', 'Спортивная'), ('Октябрьское поле', 'Октябрьское поле'), ('Измайловская', 'Измайловская'), ('Академическая', 'Академическая'), ('Проспект Вернадского', 'Проспект Вернадского'), ('Третьяковская_ж', 'Третьяковская_ж'), ('Деловой центр', 'Деловой центр'), ('Технопарк', 'Технопарк'), ('Полянка', 'Полянка'), ('Электрозаводская', 'Электрозаводская'), ('Минская', 'Минская'), ('Курская (Арбатско-Покровская)', 'Курская (Арбатско-Покровская)'), ('Алексеевская', 'Алексеевская'), ('Алма-Атинская', 'Алма-Атинская'), ('Чертановская', 'Чертановская'), ('Павелецкая_к', 'Павелецкая_к'), ('Бабушкинская', 'Бабушкинская'), ('Пионерская', 'Пионерская'), ('Семёновская', 'Семёновская'), ('Братиславская', 'Братиславская'), ('Нагорная', 'Нагорная'), ('Бульвар Адмирала Ушакова', 'Бульвар Адмирала Ушакова'), ('Киевская_г', 'Киевская_г'), ('Октябрьская_к', 'Октябрьская_к'), ('Нагатинская', 'Нагатинская'), ('Каширская_з', 'Каширская_з'), ('Планерная', 'Планерная'), ('Беляево', 'Беляево'), ('Смоленская_г', 'Смоленская_г'), ('Савёловская', 'Савёловская'), ('Смоленская_с', 'Смоленская_с'), ('Тургеневская', 'Тургеневская'), ('Красные Ворота', 'Красные Ворота'), ('Театральная', 'Театральная'), ('Тверская', 'Тверская'), ('Китай-город_ф', 'Китай-город_ф'), ('Крестьянская Застава', 'Крестьянская Застава'), ('Алтуфьево', 'Алтуфьево'), ('Проспект Мира_о', 'Проспект Мира_о'), ('Калужская', 'Калужская'), ('Новые Черёмушки', 'Новые Черёмушки'), ('Строгино', 'Строгино'), ('Севастопольская', 'Севастопольская'), ('Зябликово', 'Зябликово'), ('Александровский сад', 'Александровский сад'), ('Бутырская', 'Бутырская'), ('Волгоградский проспект', 'Волгоградский проспект'), ('Краснопресненская', 'Краснопресненская'), ('Пятницкое шоссе', 'Пятницкое шоссе'), ('Новослободская', 'Новослободская'), ('Воробьёвы горы', 'Воробьёвы горы'), ('Петровско-Разумовская', 'Петровско-Разумовская'), ('Марксистская', 'Марксистская'), ('Митино', 'Митино'), ('Водный стадион', 'Водный стадион'), ('Отрадное', 'Отрадное'), ('Маяковская', 'Маяковская'), ('Рижская', 'Рижская'), ('Трубная', 'Трубная'), ('Тушинская', 'Тушинская'), ('Сретенский бульвар', 'Сретенский бульвар'), ('Баррикадная', 'Баррикадная'), ('Комсомольская (Сокольническая)', 'Комсомольская (Сокольническая)'), ('Авиамоторная', 'Авиамоторная'), ('Перово', 'Перово'), ('Шаболовская', 'Шаболовская'), ('Нахимовский проспект', 'Нахимовский проспект'), ('Щёлковская', 'Щёлковская'), ('Новокузнецкая', 'Новокузнецкая'), ('Кропоткинская', 'Кропоткинская'), ('Сокольники', 'Сокольники'), ('Площадь Ильича', 'Площадь Ильича'), ('Шоссе Энтузиастов', 'Шоссе Энтузиастов'), ('Раменки', 'Раменки'), ('Добрынинская', 'Добрынинская'), ('Преображенская площадь', 'Преображенская площадь'), ('Белорусская_к', 'Белорусская_к'), ('Молодёжная', 'Молодёжная'), ('Владыкино', 'Владыкино'), ('Фрунзенская', 'Фрунзенская'), ('Кунцевская_г', 'Кунцевская_г'), ('Филёвский парк', 'Филёвский парк'), ('Южная', 'Южная'), ('Менделеевская', 'Менделеевская'), ('Битцевский парк', 'Битцевский парк'), ('Автозаводская', 'Автозаводская'), ('Тропарёво', 'Тропарёво'), ('Каховская', 'Каховская'), ('Домодедовская', 'Домодедовская'), ('Арбатская_г', 'Арбатская_г'), ('Сокол', 'Сокол'), ('Кожуховская', 'Кожуховская'), ('Марьино', 'Марьино'), ('Улица Горчакова', 'Улица Горчакова'), ('Чеховская', 'Чеховская'), ('Комсомольская_к', 'Комсомольская_к'), ('ВДНХ', 'ВДНХ'), ('Римская', 'Римская'), ('Марьина Роща', 'Марьина Роща'), ('Царицыно', 'Царицыно'), ('Тёплый Стан', 'Тёплый Стан'), ('Дубровка', 'Дубровка'), ('Таганская_ф', 'Таганская_ф'), ('Выставочная', 'Выставочная'), ('Волоколамская', 'Волоколамская'), ('Аэропорт', 'Аэропорт'), ('Фонвизинская', 'Фонвизинская'), ('Рязанский проспект', 'Рязанский проспект'), ('Курская (Кольцевая)', 'Курская (Кольцевая)'), ('Полежаевская', 'Полежаевская'), ('Щукинская', 'Щукинская'), ('Дмитровская', 'Дмитровская'), ('Киевская_к', 'Киевская_к'), ('Речной вокзал', 'Речной вокзал'), ('Новогиреево', 'Новогиреево'), ('Жулебино', 'Жулебино'), ('Проспект Мира_к', 'Проспект Мира_к'), ('Аннино', 'Аннино'), ('Ясенево', 'Ясенево'), ('Тульская', 'Тульская'), ('Юго-Западная', 'Юго-Западная'), ('Люблино', 'Люблино'), ('Красносельская', 'Красносельская'), ('Бауманская', 'Бауманская'), ('Выхино', 'Выхино'), ('Шипиловская', 'Шипиловская'), ('Лубянка', 'Лубянка'), ('Киевская_с', 'Киевская_с'), ('Саларьево', 'Саларьево'), ('Сходненская', 'Сходненская'), ('Свиблово', 'Свиблово'), ('Варшавская', 'Варшавская'), ('Улица Скобелевская', 'Улица Скобелевская'), ('Улица Старокачаловская', 'Улица Старокачаловская'), ('Таганская_к', 'Таганская_к'), ('Международная', 'Международная'), ('Павелецкая_з', 'Павелецкая_з'), ('Октябрьская_о', 'Октябрьская_о'), ('Пролетарская', 'Пролетарская'), ('Бибирево', 'Бибирево'), ('Пражская', 'Пражская'), ('Коломенская', 'Коломенская'), ('Парк культуры_кр', 'Парк культуры_кр'), ('Войковская', 'Войковская'), ('Площадь революции', 'Площадь революции'), ('Красногвардейская', 'Красногвардейская'), ('Коньково', 'Коньково'), ('Улица Академика Янгеля', 'Улица Академика Янгеля'), ('Беговая', 'Беговая'), ('Профсоюзная', 'Профсоюзная'), ('Крылатское', 'Крылатское'), ('Третьяковская_о', 'Третьяковская_о'), ('Петровско-Разумовская_с', 'Петровско-Разумовская_с'), ('Чистые пруды', 'Чистые пруды'), ('Кунцевская_с', 'Кунцевская_с'), ('Парк Победы_с', 'Парк Победы_с'), ('Парк культуры_к', 'Парк культуры_к'), ('Студенческая', 'Студенческая'), ('Фили', 'Фили'), ('Сухаревская', 'Сухаревская'), ('Славянский бульвар', 'Славянский бульвар'), ('Волжская', 'Волжская'), ('Тимирязевская', 'Тимирязевская'), ('Спартак', 'Спартак'), ('Кузьминки', 'Кузьминки'), ('Первомайская', 'Первомайская'), ('Ботанический сад', 'Ботанический сад'), ('Партизанская', 'Партизанская'), ('Достоевская', 'Достоевская'), ('Библиотека им.Ленина', 'Библиотека им.Ленина'), ('Петровско-Разумовская_сал', 'Петровско-Разумовская_сал'), ('Серпуховская', 'Серпуховская')])),
            ],
        ),
        migrations.CreateModel(
            name='Picket',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('date', models.DateField(unique=True)),
                ('text', models.TextField()),
                ('place_list', models.FileField(blank=True, null=True, upload_to='')),
                ('person_list', models.FileField(blank=True, null=True, upload_to='')),
                ('persons', models.ManyToManyField(blank=True, null=True, to='PicketAdminApp.Person')),
            ],
        ),
        migrations.CreateModel(
            name='Place',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('latitude', models.FloatField()),
                ('longitude', models.FloatField()),
                ('shortname', models.CharField(max_length=20)),
                ('metro', models.CharField(max_length=50, choices=[('Новоясеневская', 'Новоясеневская'), ('Кузнецкий мост', 'Кузнецкий мост'), ('Бунинская аллея', 'Бунинская аллея'), ('Парк Победы_ж', 'Парк Победы_ж'), ('Текстильщики', 'Текстильщики'), ('Медведково', 'Медведково'), ('Арбатская_с', 'Арбатская_с'), ('Лермонтовский проспект', 'Лермонтовский проспект'), ('Ленинский проспект', 'Ленинский проспект'), ('Пушкинская', 'Пушкинская'), ('Лесопарковая', 'Лесопарковая'), ('Охотный ряд', 'Охотный ряд'), ('Белорусская_з', 'Белорусская_з'), ('Ломоносовский проспект', 'Ломоносовский проспект'), ('Университет', 'Университет'), ('Чкаловская', 'Чкаловская'), ('Бульвар Рокоссовского', 'Бульвар Рокоссовского'), ('Новокосино', 'Новокосино'), ('Борисово', 'Борисово'), ('Орехово', 'Орехово'), ('Каширская_с', 'Каширская_с'), ('Китай-город_о', 'Китай-город_о'), ('Кутузовская', 'Кутузовская'), ('Багратионовская', 'Багратионовская'), ('Кантемировская', 'Кантемировская'), ('Цветной бульвар', 'Цветной бульвар'), ('Динамо', 'Динамо'), ('Румянцево', 'Румянцево'), ('Боровицкая', 'Боровицкая'), ('Улица 1905 года', 'Улица 1905 года'), ('Печатники', 'Печатники'), ('Черкизовская', 'Черкизовская'), ('Бульвар Дмитрия Донского', 'Бульвар Дмитрия Донского'), ('Мякинино', 'Мякинино'), ('Котельники', 'Котельники'), ('Спортивная', 'Спортивная'), ('Октябрьское поле', 'Октябрьское поле'), ('Измайловская', 'Измайловская'), ('Академическая', 'Академическая'), ('Проспект Вернадского', 'Проспект Вернадского'), ('Третьяковская_ж', 'Третьяковская_ж'), ('Деловой центр', 'Деловой центр'), ('Технопарк', 'Технопарк'), ('Полянка', 'Полянка'), ('Электрозаводская', 'Электрозаводская'), ('Минская', 'Минская'), ('Курская (Арбатско-Покровская)', 'Курская (Арбатско-Покровская)'), ('Алексеевская', 'Алексеевская'), ('Алма-Атинская', 'Алма-Атинская'), ('Чертановская', 'Чертановская'), ('Павелецкая_к', 'Павелецкая_к'), ('Бабушкинская', 'Бабушкинская'), ('Пионерская', 'Пионерская'), ('Семёновская', 'Семёновская'), ('Братиславская', 'Братиславская'), ('Нагорная', 'Нагорная'), ('Бульвар Адмирала Ушакова', 'Бульвар Адмирала Ушакова'), ('Киевская_г', 'Киевская_г'), ('Октябрьская_к', 'Октябрьская_к'), ('Нагатинская', 'Нагатинская'), ('Каширская_з', 'Каширская_з'), ('Планерная', 'Планерная'), ('Беляево', 'Беляево'), ('Смоленская_г', 'Смоленская_г'), ('Савёловская', 'Савёловская'), ('Смоленская_с', 'Смоленская_с'), ('Тургеневская', 'Тургеневская'), ('Красные Ворота', 'Красные Ворота'), ('Театральная', 'Театральная'), ('Тверская', 'Тверская'), ('Китай-город_ф', 'Китай-город_ф'), ('Крестьянская Застава', 'Крестьянская Застава'), ('Алтуфьево', 'Алтуфьево'), ('Проспект Мира_о', 'Проспект Мира_о'), ('Калужская', 'Калужская'), ('Новые Черёмушки', 'Новые Черёмушки'), ('Строгино', 'Строгино'), ('Севастопольская', 'Севастопольская'), ('Зябликово', 'Зябликово'), ('Александровский сад', 'Александровский сад'), ('Бутырская', 'Бутырская'), ('Волгоградский проспект', 'Волгоградский проспект'), ('Краснопресненская', 'Краснопресненская'), ('Пятницкое шоссе', 'Пятницкое шоссе'), ('Новослободская', 'Новослободская'), ('Воробьёвы горы', 'Воробьёвы горы'), ('Петровско-Разумовская', 'Петровско-Разумовская'), ('Марксистская', 'Марксистская'), ('Митино', 'Митино'), ('Водный стадион', 'Водный стадион'), ('Отрадное', 'Отрадное'), ('Маяковская', 'Маяковская'), ('Рижская', 'Рижская'), ('Трубная', 'Трубная'), ('Тушинская', 'Тушинская'), ('Сретенский бульвар', 'Сретенский бульвар'), ('Баррикадная', 'Баррикадная'), ('Комсомольская (Сокольническая)', 'Комсомольская (Сокольническая)'), ('Авиамоторная', 'Авиамоторная'), ('Перово', 'Перово'), ('Шаболовская', 'Шаболовская'), ('Нахимовский проспект', 'Нахимовский проспект'), ('Щёлковская', 'Щёлковская'), ('Новокузнецкая', 'Новокузнецкая'), ('Кропоткинская', 'Кропоткинская'), ('Сокольники', 'Сокольники'), ('Площадь Ильича', 'Площадь Ильича'), ('Шоссе Энтузиастов', 'Шоссе Энтузиастов'), ('Раменки', 'Раменки'), ('Добрынинская', 'Добрынинская'), ('Преображенская площадь', 'Преображенская площадь'), ('Белорусская_к', 'Белорусская_к'), ('Молодёжная', 'Молодёжная'), ('Владыкино', 'Владыкино'), ('Фрунзенская', 'Фрунзенская'), ('Кунцевская_г', 'Кунцевская_г'), ('Филёвский парк', 'Филёвский парк'), ('Южная', 'Южная'), ('Менделеевская', 'Менделеевская'), ('Битцевский парк', 'Битцевский парк'), ('Автозаводская', 'Автозаводская'), ('Тропарёво', 'Тропарёво'), ('Каховская', 'Каховская'), ('Домодедовская', 'Домодедовская'), ('Арбатская_г', 'Арбатская_г'), ('Сокол', 'Сокол'), ('Кожуховская', 'Кожуховская'), ('Марьино', 'Марьино'), ('Улица Горчакова', 'Улица Горчакова'), ('Чеховская', 'Чеховская'), ('Комсомольская_к', 'Комсомольская_к'), ('ВДНХ', 'ВДНХ'), ('Римская', 'Римская'), ('Марьина Роща', 'Марьина Роща'), ('Царицыно', 'Царицыно'), ('Тёплый Стан', 'Тёплый Стан'), ('Дубровка', 'Дубровка'), ('Таганская_ф', 'Таганская_ф'), ('Выставочная', 'Выставочная'), ('Волоколамская', 'Волоколамская'), ('Аэропорт', 'Аэропорт'), ('Фонвизинская', 'Фонвизинская'), ('Рязанский проспект', 'Рязанский проспект'), ('Курская (Кольцевая)', 'Курская (Кольцевая)'), ('Полежаевская', 'Полежаевская'), ('Щукинская', 'Щукинская'), ('Дмитровская', 'Дмитровская'), ('Киевская_к', 'Киевская_к'), ('Речной вокзал', 'Речной вокзал'), ('Новогиреево', 'Новогиреево'), ('Жулебино', 'Жулебино'), ('Проспект Мира_к', 'Проспект Мира_к'), ('Аннино', 'Аннино'), ('Ясенево', 'Ясенево'), ('Тульская', 'Тульская'), ('Юго-Западная', 'Юго-Западная'), ('Люблино', 'Люблино'), ('Красносельская', 'Красносельская'), ('Бауманская', 'Бауманская'), ('Выхино', 'Выхино'), ('Шипиловская', 'Шипиловская'), ('Лубянка', 'Лубянка'), ('Киевская_с', 'Киевская_с'), ('Саларьево', 'Саларьево'), ('Сходненская', 'Сходненская'), ('Свиблово', 'Свиблово'), ('Варшавская', 'Варшавская'), ('Улица Скобелевская', 'Улица Скобелевская'), ('Улица Старокачаловская', 'Улица Старокачаловская'), ('Таганская_к', 'Таганская_к'), ('Международная', 'Международная'), ('Павелецкая_з', 'Павелецкая_з'), ('Октябрьская_о', 'Октябрьская_о'), ('Пролетарская', 'Пролетарская'), ('Бибирево', 'Бибирево'), ('Пражская', 'Пражская'), ('Коломенская', 'Коломенская'), ('Парк культуры_кр', 'Парк культуры_кр'), ('Войковская', 'Войковская'), ('Площадь революции', 'Площадь революции'), ('Красногвардейская', 'Красногвардейская'), ('Коньково', 'Коньково'), ('Улица Академика Янгеля', 'Улица Академика Янгеля'), ('Беговая', 'Беговая'), ('Профсоюзная', 'Профсоюзная'), ('Крылатское', 'Крылатское'), ('Третьяковская_о', 'Третьяковская_о'), ('Петровско-Разумовская_с', 'Петровско-Разумовская_с'), ('Чистые пруды', 'Чистые пруды'), ('Кунцевская_с', 'Кунцевская_с'), ('Парк Победы_с', 'Парк Победы_с'), ('Парк культуры_к', 'Парк культуры_к'), ('Студенческая', 'Студенческая'), ('Фили', 'Фили'), ('Сухаревская', 'Сухаревская'), ('Славянский бульвар', 'Славянский бульвар'), ('Волжская', 'Волжская'), ('Тимирязевская', 'Тимирязевская'), ('Спартак', 'Спартак'), ('Кузьминки', 'Кузьминки'), ('Первомайская', 'Первомайская'), ('Ботанический сад', 'Ботанический сад'), ('Партизанская', 'Партизанская'), ('Достоевская', 'Достоевская'), ('Библиотека им.Ленина', 'Библиотека им.Ленина'), ('Петровско-Разумовская_сал', 'Петровско-Разумовская_сал'), ('Серпуховская', 'Серпуховская')])),
                ('description', models.TextField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Post',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('title', models.CharField(max_length=200)),
                ('text', models.TextField()),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Spot',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('person', models.ForeignKey(blank=True, null=True, to='PicketAdminApp.Person')),
                ('picket', models.ForeignKey(to='PicketAdminApp.Picket')),
                ('place', models.ForeignKey(blank=True, null=True, to='PicketAdminApp.Place')),
            ],
        ),
        migrations.CreateModel(
            name='Task',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=20, choices=[('poll_picket', 'poll picket'), ('accept_picket', 'accept picket'), ('info_picket', 'info picket'), ('geo_picket', 'geo picket')])),
                ('status', models.BooleanField(default=True)),
                ('date', models.DateField()),
                ('data', models.CharField(max_length=200, blank=True, null=True)),
            ],
        ),
        migrations.AddField(
            model_name='picket',
            name='places',
            field=models.ManyToManyField(blank=True, null=True, to='PicketAdminApp.Place'),
        ),
    ]
Esempio n. 17
0
class RuneInstance(Rune):
    # Upgrade success rate based on rune level
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    type = models.IntegerField(choices=Rune.TYPE_CHOICES)
    owner = models.ForeignKey(Summoner, on_delete=models.CASCADE)
    com2us_id = models.BigIntegerField(blank=True, null=True)
    assigned_to = models.ForeignKey(MonsterInstance,
                                    on_delete=models.SET_NULL,
                                    blank=True,
                                    null=True)
    marked_for_sale = models.BooleanField(default=False)
    notes = models.TextField(null=True, blank=True)

    __original_assigned_to_id = None

    # Old substat fields to be removed later, but still used
    substat_1 = models.IntegerField(choices=Rune.STAT_CHOICES,
                                    null=True,
                                    blank=True)
    substat_1_value = models.IntegerField(null=True, blank=True)
    substat_1_craft = models.IntegerField(choices=RuneCraft.CRAFT_CHOICES,
                                          null=True,
                                          blank=True)
    substat_2 = models.IntegerField(choices=Rune.STAT_CHOICES,
                                    null=True,
                                    blank=True)
    substat_2_value = models.IntegerField(null=True, blank=True)
    substat_2_craft = models.IntegerField(choices=RuneCraft.CRAFT_CHOICES,
                                          null=True,
                                          blank=True)
    substat_3 = models.IntegerField(choices=Rune.STAT_CHOICES,
                                    null=True,
                                    blank=True)
    substat_3_value = models.IntegerField(null=True, blank=True)
    substat_3_craft = models.IntegerField(choices=RuneCraft.CRAFT_CHOICES,
                                          null=True,
                                          blank=True)
    substat_4 = models.IntegerField(choices=Rune.STAT_CHOICES,
                                    null=True,
                                    blank=True)
    substat_4_value = models.IntegerField(null=True, blank=True)
    substat_4_craft = models.IntegerField(choices=RuneCraft.CRAFT_CHOICES,
                                          null=True,
                                          blank=True)

    class Meta:
        ordering = ['slot', 'type', 'level']

    def __init__(self, *args, **kwargs):
        super(RuneInstance, self).__init__(*args, **kwargs)
        self.__original_assigned_to_id = self.assigned_to_id

    def clean(self):
        super().clean()

        if self.assigned_to is not None and (
                self.assigned_to.runeinstance_set.filter(
                    slot=self.slot).exclude(pk=self.pk).count() > 0):
            raise ValidationError('Monster already has rune in slot %(slot)s.',
                                  params={
                                      'slot': self.slot,
                                  },
                                  code='slot_occupied')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if self.assigned_to:
            # Check no other runes are in this slot
            for rune in RuneInstance.objects.filter(
                    assigned_to=self.assigned_to,
                    slot=self.slot).exclude(pk=self.pk):
                rune.assigned_to = None
                rune.save()

            # Trigger stat calc update on the assigned monster
            self.assigned_to.save()

            # Update default rune build on that monster
            # TODO: Remove this once rune builds are default method of working with equipped runes
            self.assigned_to._initialize_rune_build()
        else:
            # TODO: Remove this once rune builds are default method of working with equipped runes
            if self.__original_assigned_to_id is not None and self.assigned_to is None:
                # Rune was removed, update rune build on that monster
                MonsterInstance.objects.get(pk=self.__original_assigned_to_id
                                            )._initialize_rune_build()
class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0006_require_contenttypes_0002'),
    ]

    operations = [
        migrations.CreateModel(
            name='LUser',
            fields=[
                ('id',
                 models.AutoField(serialize=False,
                                  primary_key=True,
                                  auto_created=True,
                                  verbose_name='ID')),
                ('is_admin', models.BooleanField(default=False)),
                ('password',
                 models.CharField(verbose_name='password', max_length=128)),
                ('last_login',
                 models.DateTimeField(blank=True,
                                      null=True,
                                      verbose_name='last login')),
                ('email',
                 models.EmailField(unique=True,
                                   max_length=255,
                                   verbose_name=b'email address')),
                ('is_active', models.BooleanField(default=True)),
                ('is_user_add_api_account',
                 models.BooleanField(default=False)),
                ('lat', models.FloatField(null=True, blank=True)),
                ('lon', models.FloatField(null=True, blank=True)),
            ],
            options={
                'abstract': False,
                'verbose_name_plural': 'users',
                'verbose_name': 'user',
            },
            managers=[],
        ),
        migrations.CreateModel(
            name='Bag',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('name', models.CharField(max_length=1024, db_index=True)),
                ('owner', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
                ('imei',
                 models.BigIntegerField(unique=True, verbose_name=b'IMEI')),
                ('geo_fence', models.FloatField(default=10)),
                ('tracking', models.BooleanField(default=True, db_index=True)),
                ('lat', models.FloatField(null=True, blank=True)),
                ('lon', models.FloatField(null=True, blank=True)),
                ('altitude', models.FloatField(null=True, blank=True)),
                ('speed', models.FloatField(null=True, blank=True)),
                ('distance', models.FloatField(null=True, blank=True)),
                ('battery',
                 models.FloatField(
                     default=1,
                     validators=[
                         django.core.validators.MinValueValidator(0),
                         django.core.validators.MaxValueValidator(1)
                     ])),
                ('charging', models.BooleanField(default=False)),
                ('image',
                 imagekit.models.fields.ProcessedImageField(
                     null=True,
                     upload_to=lamonte_core.models.image_path,
                     blank=True)),
                ('nearby', models.BooleanField(default=False, db_index=True)),
            ],
            options={
                'ordering': ['id'],
                'verbose_name': 'Bag',
                'verbose_name_plural': 'Bags',
            },
        ),
        migrations.AlterModelOptions(
            name='LUser',
            options={
                'verbose_name_plural': 'Users',
                'verbose_name': 'User'
            },
        ),
        migrations.CreateModel(
            name='Contact',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('name', models.CharField(max_length=1024, db_index=True)),
                ('iso', models.CharField(max_length=3)),
                ('phone', models.CharField(max_length=1024)),
                ('e164Phone', models.CharField(max_length=1024)),
                ('formattedPhone', models.CharField(max_length=1024)),
                ('bag',
                 models.ForeignKey(related_name='contacts',
                                   to='lamonte_core.Bag')),
            ],
            options={
                'ordering': ['name'],
                'verbose_name': 'Contact Assigned for Bag',
                'verbose_name_plural': 'Contacts Assigned for Bag',
            },
        ),
        migrations.CreateModel(
            name='DeviceDataEntry',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('data', models.TextField()),
                ('altitude', models.FloatField(null=True, blank=True)),
                ('battery', models.FloatField(null=True, blank=True)),
                ('cell_id', models.IntegerField(null=True, blank=True)),
                ('coarse', models.FloatField(null=True, blank=True)),
                ('imei',
                 models.BigIntegerField(db_index=True, null=True, blank=True)),
                ('lat', models.FloatField(null=True, blank=True)),
                ('lon', models.FloatField(null=True, blank=True)),
                ('speed', models.FloatField(null=True, blank=True)),
                ('temperature', models.FloatField(null=True, blank=True)),
                ('timestamp', models.IntegerField(null=True, blank=True)),
                ('wifi_mac_id_1', models.CharField(max_length=64, blank=True)),
                ('wifi_mac_id_2', models.CharField(max_length=64, blank=True)),
                ('wifi_mac_id_3', models.CharField(max_length=64, blank=True)),
                ('wifi_mac_id_4', models.CharField(max_length=64, blank=True)),
                ('wifi_mac_id_5', models.CharField(max_length=64, blank=True)),
                ('wifi_ssid_1', models.CharField(max_length=32, blank=True)),
                ('wifi_ssid_2', models.CharField(max_length=32, blank=True)),
                ('wifi_ssid_3', models.CharField(max_length=32, blank=True)),
                ('wifi_ssid_4', models.CharField(max_length=32, blank=True)),
                ('wifi_ssid_5', models.CharField(max_length=32, blank=True)),
                ('bag',
                 models.ForeignKey(related_name='device_data_entries',
                                   blank=True,
                                   to='lamonte_core.Bag',
                                   null=True)),
            ],
            options={
                'ordering': ['-created'],
                'verbose_name': 'Device Data Entry',
                'verbose_name_plural': 'Device Data Entries',
            },
        ),
    ]
class Space(models.Model):
    """ Common storage space information.

    Knows what protocol to use to access a storage space, but all protocol
    specific information is in children classes with ForeignKeys to Space."""
    uuid = UUIDField(editable=False, unique=True, version=4,
        help_text=_l("Unique identifier"))

    # Max length 8 (see access_protocol definition)
    ARKIVUM = 'ARKIVUM'
    DATAVERSE = 'DV'
    DURACLOUD = 'DC'
    DSPACE = 'DSPACE'
    DSPACE_REST = 'DSPC_RST'
    FEDORA = 'FEDORA'
    LOCAL_FILESYSTEM = 'FS'
    LOM = 'LOM'
    NFS = 'NFS'
    PIPELINE_LOCAL_FS = 'PIPE_FS'
    SWIFT = 'SWIFT'
    GPG = 'GPG'
    S3 = 'S3'
    # These will not be displayed in the Space Create GUI (see locations/forms.py)
    BETA_PROTOCOLS = {DSPACE_REST}
    OBJECT_STORAGE = {DATAVERSE, DSPACE, DSPACE_REST, DURACLOUD, SWIFT, S3}
    ACCESS_PROTOCOL_CHOICES = (
        (ARKIVUM, _l('Arkivum')),
        (DATAVERSE, _l('Dataverse')),
        (DURACLOUD, _l('DuraCloud')),
        (DSPACE, _l('DSpace via SWORD2 API')),
        (DSPACE_REST, _l('DSpace via REST API')),
        (FEDORA, _l("FEDORA via SWORD2")),
        (GPG, _l("GPG encryption on Local Filesystem")),
        (LOCAL_FILESYSTEM, _l("Local Filesystem")),
        (LOM, _l("LOCKSS-o-matic")),
        (NFS, _l("NFS")),
        (PIPELINE_LOCAL_FS, _l("Pipeline Local Filesystem")),
        (SWIFT, _l("Swift")),
        (S3, _l("S3")),
    )
    access_protocol = models.CharField(max_length=8,
        choices=ACCESS_PROTOCOL_CHOICES,
        verbose_name=_l("Access protocol"),
        help_text=_l("How the space can be accessed."))
    size = models.BigIntegerField(default=None, null=True, blank=True,
        verbose_name=_l("Size"),
        help_text=_l("Size in bytes (optional)"))
    used = models.BigIntegerField(default=0,
        verbose_name=_l("Used"),
        help_text=_l("Amount used in bytes"))
    path = models.TextField(default='', blank=True,
        verbose_name=_l("Path"),
        help_text=_l("Absolute path to the space on the storage service machine."))
    staging_path = models.TextField(validators=[validate_space_path],
        verbose_name=_l("Staging path"),
        help_text=_l("Absolute path to a staging area.  Must be UNIX filesystem compatible, preferably on the same filesystem as the path."))
    verified = models.BooleanField(default=False,
        verbose_name=_l("Verified"),
        help_text=_l("Whether or not the space has been verified to be accessible."))
    last_verified = models.DateTimeField(default=None, null=True, blank=True,
        verbose_name=_l("Last verified"),
        help_text=_l("Time this location was last verified to be accessible."))

    class Meta:
        verbose_name = _l('Space')
        app_label = 'locations'

    def __unicode__(self):
        return u"{uuid}: {path} ({access_protocol})".format(
            uuid=self.uuid,
            access_protocol=self.get_access_protocol_display(),
            path=self.path,
        )

    def clean(self):
        # Object storage spaces do not require a path, or for it to start with /
        if self.access_protocol not in self.OBJECT_STORAGE:
            if not self.path:
                raise ValidationError(_('Path is required'))
            validate_space_path(self.path)

    def get_child_space(self):
        """ Returns the protocol-specific space object. """
        # Importing PROTOCOL here because importing locations.constants at the
        # top of the file causes a circular dependency
        from ..constants import PROTOCOL
        protocol_model = PROTOCOL[self.access_protocol]['model']
        protocol_space = protocol_model.objects.get(space=self)
        # TODO try-catch AttributeError if remote_user or remote_name not exist?
        return protocol_space

    def browse(self, path, *args, **kwargs):
        """
        Return information about the objects (files, directories) at `path`.

        Attempts to call the child space's implementation.  If not found, falls
        back to looking for the path locally.

        Returns a dictionary with keys 'entries', 'directories' and 'properties'.

        'entries' is a list of strings, one for each entry in that directory, both file-like and folder-like.
        'directories' is a list of strings for each folder-like entry. Each entry should also be listed in 'entries'.
        'properties' is a dictionary that may contain additional information for the entries.  Keys are the entry name found in 'entries', values are a dictionary containing extra information. 'properties' may not contain all values from 'entries'.

        E.g.
        {
            'entries': ['BagTransfer.zip', 'Images', 'Multimedia', 'OCRImage'],
            'directories': ['Images', 'Multimedia', 'OCRImage'],
            'properties': {
                'Images': {'object count': 10},
                'Multimedia': {'object count': 7},
                'OCRImage': {'object count': 1}
            },
        }

        Values in the properties dict vary depending on the providing Space but may include:
        'size': Size of the object
        'object count': Number of objects in the directory, including children
        'timestamp': Last modified timestamp.
        'verbose name': Verbose name of the object
        See each Space's browse for details.

        :param str path: Full path to return info for
        :return: Dictionary of object information detailed above.
        """
        LOGGER.info('path: %s', path)
        try:
            return self.get_child_space().browse(path, *args, **kwargs)
        except AttributeError:
            LOGGER.debug('Falling back to default browse local', exc_info=False)
            return self.browse_local(path)

    def delete_path(self, delete_path, *args, **kwargs):
        """
        Deletes `delete_path` stored in this space.

        `delete_path` is a full path in this space.

        If not implemented in the child space, looks locally.
        """
        # Enforce delete_path is in self.path
        if not delete_path.startswith(self.path):
            raise ValueError(
                _('%(delete_path)s is not within %(path)s'),
                {'delete_path': delete_path, 'path': self.path})
        try:
            return self.get_child_space().delete_path(delete_path, *args, **kwargs)
        except AttributeError:
            return self._delete_path_local(delete_path)

    def posix_move(self, source_path, destination_path, destination_space, package=None):
        """
        Move self.path/source_path direct to destination_space.path/destination_path bypassing staging.
        """
        if (not hasattr(self.get_child_space(), 'posix_move') or
                not hasattr(destination_space.get_child_space(), 'posix_move')):
            LOGGER.debug('posix_move: not supported as %s and %s are not both POSIX filesystems',
                type(self.get_child_space()),
                type(destination_space.get_child_space()))
            raise PosixMoveUnsupportedError()

        LOGGER.debug('posix_move: source_path: %s', source_path)
        LOGGER.debug('posix_move: destination_path: %s', destination_path)
        LOGGER.debug('posix_move: destination_space.path: %s', destination_space.path)

        source_path = os.path.join(self.path, source_path)

        if os.path.isabs(destination_path):
            destination_path = destination_path.lstrip(os.sep)

        abs_destination_path = os.path.join(destination_space.path, destination_path)

        return self.get_child_space().posix_move(
            source_path, abs_destination_path, destination_space, package)

    def move_to_storage_service(self, source_path, destination_path,
                                destination_space, *args, **kwargs):
        """ Move source_path to destination_path in the staging area of destination_space.

        If source_path is not an absolute path, it is assumed to be relative to
        Space.path.

        destination_path must be relative and destination_space.staging_path
        MUST be locally accessible to the storage service.

        This is implemented by the child protocol spaces.
        """
        LOGGER.debug('TO: src: %s', source_path)
        LOGGER.debug('TO: dst: %s', destination_path)
        LOGGER.debug('TO: staging: %s', destination_space.staging_path)

        # TODO enforce source_path is inside self.path
        # Path pre-processing
        source_path = os.path.join(self.path, source_path)
        # dest_path must be relative
        if os.path.isabs(destination_path):
            destination_path = destination_path.lstrip(os.sep)
            # Alternative implementation
            # os.path.join(*destination_path.split(os.sep)[1:]) # Strips up to first os.sep
        destination_path = os.path.join(destination_space.staging_path, destination_path)

        try:
            self.get_child_space().move_to_storage_service(
                source_path, destination_path, destination_space, *args, **kwargs)
        except AttributeError:
            raise NotImplementedError(_('%(protocol)s space has not implemented %(method)s') % {'protocol': self.get_access_protocol_display(), 'method': 'move_to_storage_service'})

    def post_move_to_storage_service(self, *args, **kwargs):
        """ Hook for any actions that need to be taken after moving to the storage service. """
        try:
            self.get_child_space().post_move_to_storage_service(*args, **kwargs)
        except AttributeError:
            # This is optional for the child class to implement
            pass

    def _move_from_path_mangling(self, staging_path, destination_path):
        """
        Does path pre-processing before passing to move_from_* functions.

        Given a staging_path relative to self.staging_path, converts to an absolute path.
        If staging_path is absolute (starts with /), force to be relative.
        If staging_path is a directory, ensure ends with /
        Given a destination_path relative to this space, converts to an absolute path.

        :param str staging_path: Path to the staging copy relative to the SS internal location.
        :param str destination_path: Path to the destination copy relative to this Space's path.
        :return: Tuple of absolute paths (staging_path, destination_path)
        """
        # Path pre-processing
        # source_path must be relative
        if os.path.isabs(staging_path):
            staging_path = staging_path.lstrip(os.sep)
            # Alternate implementation:
            # os.path.join(*staging_path.split(os.sep)[1:]) # Strips up to first os.sep
        staging_path = os.path.join(self.staging_path, staging_path)
        if os.path.isdir(staging_path):
            staging_path += os.sep
        destination_path = os.path.join(self.path, destination_path)

        # TODO enforce destination_path is inside self.path

        return staging_path, destination_path

    def move_from_storage_service(self, source_path, destination_path,
                                  *args, **kwargs):
        """ Move source_path in this Space's staging area to destination_path in this Space.

        That is, moves self.staging_path/source_path to self.path/destination_path.

        If destination_path is not an absolute path, it is assumed to be
        relative to Space.path.

        source_path must be relative to self.staging_path.

        This is implemented by the child protocol spaces.
        """
        LOGGER.debug('FROM: src: %s', source_path)
        LOGGER.debug('FROM: dst: %s', destination_path)

        source_path, destination_path = self._move_from_path_mangling(source_path, destination_path)
        child_space = self.get_child_space()
        if hasattr(child_space, 'move_from_storage_service'):
            return child_space.move_from_storage_service(
                source_path, destination_path, *args, **kwargs)
        else:
            raise NotImplementedError(_('%(protocol)s space has not implemented %(method)s') % {'protocol': self.get_access_protocol_display(), 'method': 'move_from_storage_service'})

    def post_move_from_storage_service(self, staging_path, destination_path, package=None, *args, **kwargs):
        """
        Hook for any actions that need to be taken after moving from the storage
        service to the final destination.

        :param str staging_path: Path to the staging copy relative to the SS internal location. Can be None if destination_path is also None.
        :param str destination_path: Path to the destination copy relative to this Space's path. Can be None if staging_path is also None.
        :param package: (Optional) :class:`Package` that is being moved.
        """
        if staging_path is None or destination_path is None:
            staging_path = destination_path = None
        if staging_path and destination_path:
            staging_path, destination_path = self._move_from_path_mangling(staging_path, destination_path)
        try:
            self.get_child_space().post_move_from_storage_service(
                staging_path=staging_path,
                destination_path=destination_path,
                package=package,
                *args, **kwargs)
        except AttributeError:
            # This is optional for the child class to implement
            pass
        # Delete staging copy
        if staging_path != destination_path:
            try:
                if os.path.isdir(staging_path):
                    # Need to convert this to an str - if this is a
                    # unicode string, rmtree will use os.path.join
                    # on the directory and the names of its children,
                    # which can result in an attempt to join mixed encodings;
                    # this blows up if the filename cannot be converted to
                    # unicode
                    shutil.rmtree(utils.coerce_str(os.path.normpath(staging_path)))
                elif os.path.isfile(staging_path):
                    os.remove(os.path.normpath(staging_path))
            except OSError:
                logging.warning('Unable to remove %s', staging_path, exc_info=True)

    def update_package_status(self, package):
        """
        Check and update the status of `package` stored in this Space.
        """
        try:
            return self.get_child_space().update_package_status(package)
        except AttributeError:
            message = _('%(protocol)s space has not implemented %(method)s') % {'protocol': self.get_access_protocol_display(), 'method': 'update_package_status'}
            return (None, message)

    def check_package_fixity(self, package):
        """
        Check and return the fixity status of `package` stored in this space.

        :param package: Package to check
        """
        child = self.get_child_space()
        if hasattr(child, 'check_package_fixity'):
            return child.check_package_fixity(package)
        else:
            raise NotImplementedError(
                _('Space %(protocol)s does not implement check_package_fixity') %
                {'protocol': self.get_access_protocol_display()}
            )

    # HELPER FUNCTIONS

    def move_rsync(self, source, destination, try_mv_local=False, assume_rsync_daemon=False, rsync_password=None):
        """ Moves a file from source to destination.

        By default, uses rsync to move files.
        All directories leading to destination must exist; Space.create_local_directory may be useful.

        If try_mv_local is True, will attempt to use os.rename, which only works on the same device.
        This will not leave a copy at the source.

        :param source: Path to source file or directory. May have user@host: at beginning.
        :param destination: Path to destination file or directory. May have user@host: at the beginning.
        :param bool try_mv_local: If true, try moving/renaming instead of copying.  Should be False if source or destination specify a user@host.  Warning: this will not leave a copy at the source.
        :param bool assume_rsync_daemon: If true, will use rsync daemon-style commands instead of the default rsync with remote shell transport
        :param rsync_password: used if assume_rsync_daemon is true, to specify value of RSYNC_PASSWORD environment variable
        """
        source = utils.coerce_str(source)
        destination = utils.coerce_str(destination)
        LOGGER.info("Moving from %s to %s", source, destination)

        if source == destination:
            return

        if try_mv_local:
            # Try using mv, and if that fails, fallback to rsync
            chmod_command = ['chmod', '--recursive', 'ug+rw,o+r', destination]
            try:
                os.rename(source, destination)
                # Set permissions (rsync does with --chmod=ugo+rw)
                subprocess.call(chmod_command)
                return
            except OSError:
                LOGGER.debug('os.rename failed, trying with normalized paths')
            source_norm = os.path.normpath(source)
            dest_norm = os.path.normpath(destination)
            try:
                os.rename(source_norm, dest_norm)
                # Set permissions (rsync does with --chmod=ugo+rw)
                subprocess.call(chmod_command)
                return
            except OSError:
                LOGGER.debug('os.rename failed, falling back to rsync. Source: %s; Destination: %s', source_norm, dest_norm)

        # Rsync file over
        # TODO Do this asyncronously, with restarting failed attempts
        command = ['rsync', '-t', '-O', '--protect-args', '-vv',
                   '--chmod=Fug+rw,o-rwx,Dug+rwx,o-rwx',
                   '-r', source, destination]
        LOGGER.info("rsync command: %s", command)
        kwargs = {'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT}
        if assume_rsync_daemon:
            kwargs['env'] = {'RSYNC_PASSWORD': rsync_password}
        p = subprocess.Popen(command, **kwargs)
        stdout, _ = p.communicate()
        if p.returncode != 0:
            s = "Rsync failed with status {}: {}".format(p.returncode, stdout)
            LOGGER.warning(s)
            raise StorageException(s)

    def create_local_directory(self, path, mode=None):
        """
        Creates directory structure for `path` with `mode` (default 775).
        :param path: path to create the directories for.  Should end with a / or
            a filename, or final directory may not be created. If path is empty,
            no directories are created.
        :param mode: (optional) Permissions to create the directories with
            represented in octal (like bash or the stat module)
        """
        if mode is None:
            mode = (stat.S_IRUSR + stat.S_IWUSR + stat.S_IXUSR +
                    stat.S_IRGRP + stat.S_IWGRP + stat.S_IXGRP +
                    stat.S_IROTH + stat.S_IXOTH)
        dir_path = os.path.dirname(path)
        if not dir_path:
            return
        try:
            os.makedirs(dir_path, mode)
        except os.error as e:
            # If the leaf node already exists, that's fine
            if e.errno != errno.EEXIST:
                LOGGER.warning("Could not create storage directory: %s", e)
                raise

        # os.makedirs may ignore the mode when creating directories, so force
        # the permissions here. Some spaces (eg CIFS) doesn't allow chmod, so
        # wrap it in a try-catch and ignore the failure.
        try:
            os.chmod(os.path.dirname(path), mode)
        except os.error as e:
            LOGGER.warning(e)

    def create_rsync_directory(self, destination_path, user, host):
        """
        Creates a remote directory structure for destination_path.

        :param path: path to create the directories for.  Should end with a / or
            a filename, or final directory may not be created. If path is empty,
            no directories are created.
        :param user: Username on remote host
        :param host: Hostname of remote host
        """
        # Assemble a set of directories to create on the remote server;
        # these will be created one at a time
        directories = []
        path = destination_path
        while path != '' and path != '/':
            directories.insert(0, path)
            path = os.path.dirname(path)

        # Syncing an empty directory will ensure no files get transferred
        temp_dir = os.path.join(tempfile.mkdtemp(), '')

        # Creates the destination_path directory without copying any files
        # Dir must end in a / for rsync to create it
        for directory in directories:
            path = os.path.join(os.path.dirname(directory), '')
            path = "{}@{}:{}".format(user, host, utils.coerce_str(path))
            cmd = ['rsync', '-vv', '--protect-args', '--chmod=ug=rwx,o=rx', '--recursive', temp_dir, path]
            LOGGER.info("rsync path creation command: %s", cmd)
            try:
                subprocess.check_call(cmd)
            except subprocess.CalledProcessError as e:
                shutil.rmtree(temp_dir)
                LOGGER.warning("rsync path creation failed: %s", e)
                raise

        shutil.rmtree(temp_dir)

    def browse_local(self, path):
        """
        Returns browse results for a locally accessible filesystem.

        Properties provided:
        'size': Size of the object, as determined by os.path.getsize. May be misleading for directories, suggest use 'object count'
        'object count': Number of objects in the directory, including children
        """
        if isinstance(path, unicode):
            path = str(path)
        if not os.path.exists(path):
            LOGGER.info('%s in %s does not exist', path, self)
            return {'directories': [], 'entries': [], 'properties': {}}
        return path2browse_dict(path)

    def browse_rsync(self, path, ssh_key=None, assume_rsync_daemon=False, rsync_password=None):
        """
        Returns browse results for a ssh (rsync) accessible space.

        See Space.browse for full documentation.

        Properties provided:
        'size': Size of the object
        'timestamp': Last modified timestamp of the object or directory

        :param path: Path to query, including user & hostname. E.g. user@host:/path/to/browse/  Must end in with / to browse directories.
        :param ssh_key: Path to the SSH key on disk. If None, will use default.
        :param bool assume_rsync_daemon: If true, will use rsync daemon-style commands instead of the default rsync with remote shell transport
        :param rsync_password: used if assume_rsync_daemon is true, to specify value of RSYNC_PASSWORD environment variable
        :return: See docstring for Space.browse
        """
        if ssh_key is None:
            ssh_key = '/var/lib/archivematica/.ssh/id_rsa'

        # Form command string used to get entries
        command = ['rsync',
                   '--protect-args',
                   '--list-only',
                   '--exclude', '.*',  # Ignore hidden files
                   ]
        if not assume_rsync_daemon:
            # Specify identity file
            command += ['--rsh', 'ssh -i ' + ssh_key]
        command += [path]

        LOGGER.info('rsync list command: %s', command)
        LOGGER.debug('"%s"', '" "'.join(command))  # For copying to shell
        try:
            env = os.environ.copy()
            if assume_rsync_daemon:
                env['RSYNC_PASSWORD'] = rsync_password
            output = subprocess.check_output(command, env=env)
        except Exception as e:
            LOGGER.warning("rsync list failed: %s", e, exc_info=True)
            entries = []
            directories = []
        else:
            output = output.splitlines()
            # Output is lines in format:
            # <type><permissions>  <size>  <date> <time> <path>
            # Eg: drwxrws---          4,096 2015/03/02 17:05:20 tmp
            # Eg: -rw-r--r--            201 2013/05/13 13:26:48 LICENSE.md
            # Eg: lrwxrwxrwx             78 2015/02/19 12:13:40 sharedDirectory
            # Parse out the path and type
            # Define groups for type, permissions, size, timestamp and name
            regex = r'^(?P<type>.)(?P<permissions>.{9}) +(?P<size>[\d,]+) (?P<timestamp>..../../.. ..:..:..) (?P<name>.*)$'
            matches = [re.match(regex, e) for e in output]
            # Take the last entry. Ignore empty lines and '.'
            entries = [e.group('name') for e in matches
                if e and e.group('name') != '.']
            # Only items whose type is not '-'. Links count as dirs.
            directories = [e.group('name') for e in matches
                if e and e.group('name') != '.' and e.group('type') != '-']
            # Generate properties for each entry
            properties = {}
            for e in matches:
                name = e.group('name')
                if name not in entries:
                    continue
                properties[name] = {}
                properties[name]['timestamp'] = datetime.datetime.strptime(e.group('timestamp'), '%Y/%m/%d %H:%M:%S').isoformat()
                if name not in directories:
                    properties[name]['size'] = int(e.group('size').replace(',', ''))

        directories = sorted(directories, key=lambda s: s.lower())
        entries = sorted(entries, key=lambda s: s.lower())
        LOGGER.debug('entries: %s', entries)
        LOGGER.debug('directories: %s', directories)
        return {'directories': directories, 'entries': entries}

    def _delete_path_local(self, delete_path):
        """
        Deletes `delete_path` in this space, assuming it is locally accessible.
        """
        try:
            if os.path.isfile(delete_path):
                os.remove(delete_path)
            if os.path.isdir(delete_path):
                shutil.rmtree(delete_path)
        except (os.error, shutil.Error):
            LOGGER.warning("Error deleting package %s", delete_path, exc_info=True)
            raise
Esempio n. 20
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=[(b'string', b'String'),
                                           (b'number', b'Number'),
                                           (b'integer', b'Integer'),
                                           (b'boolean', b'Boolean'),
                                           (b'binary', b'Binary')],
                                  max_length=80)),
                ('value', models.TextField(blank=True, db_column=b'value')),
            ],
        ),
        migrations.CreateModel(
            name='MapStoreData',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('blob', jsonfield.fields.JSONField(default={})),
            ],
        ),
        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=[b'id'],
                               name='mapstore2_a_id_cd23a9_idx'),
        ),
        migrations.AddIndex(
            model_name='mapstoreresource',
            index=models.Index(fields=[b'name'],
                               name='mapstore2_a_name_35c0a1_idx'),
        ),
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Categoria',
            fields=[
                ('idCategoria',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('categoria', models.TextField()),
            ],
            options={
                'ordering': ('categoria', ),
            },
        ),
        migrations.CreateModel(
            name='Empresa',
            fields=[
                ('idEmpresa',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('empresa', models.TextField()),
            ],
            options={
                'ordering': ('empresa', ),
            },
        ),
        migrations.CreateModel(
            name='Genero',
            fields=[
                ('idGenero',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('genero', models.TextField()),
            ],
            options={
                'ordering': ('genero', ),
            },
        ),
        migrations.CreateModel(
            name='HistoricoJuego',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('fecha', models.DateField()),
                ('precioVenta', models.FloatField()),
                ('precioCompra', models.FloatField()),
                ('precioIntercambio', models.FloatField()),
            ],
            options={
                'ordering': ('fecha', ),
            },
        ),
        migrations.CreateModel(
            name='ImagenJuego',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('urlImagen', models.URLField()),
            ],
        ),
        migrations.CreateModel(
            name='Juego',
            fields=[
                ('sku',
                 models.BigIntegerField(primary_key=True, serialize=False)),
                ('idIGDB', models.BigIntegerField(null=True)),
                ('nombre', models.TextField()),
                ('portada', models.URLField()),
                ('precioVenta', models.FloatField()),
                ('precioCompra', models.FloatField()),
                ('precioIntercambio', models.FloatField()),
                ('fechaSalida', models.DateField(null=True)),
                ('actualizado', models.DateField()),
                ('categoria',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='lowpricex_app.Categoria')),
                ('desarrolladores',
                 models.ManyToManyField(related_name='desarrolladores',
                                        to='lowpricex_app.Empresa')),
                ('generos', models.ManyToManyField(to='lowpricex_app.Genero')),
            ],
            options={
                'ordering': ('nombre', ),
            },
        ),
        migrations.CreateModel(
            name='Keyword',
            fields=[
                ('idKeyword',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('keyword', models.TextField()),
            ],
            options={
                'ordering': ('keyword', ),
            },
        ),
        migrations.CreateModel(
            name='Plataforma',
            fields=[
                ('idPlataforma',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('nombre', models.TextField()),
                ('abreviatura', models.TextField()),
                ('logo', models.URLField()),
            ],
            options={
                'ordering': ('abreviatura', ),
            },
        ),
        migrations.CreateModel(
            name='Tema',
            fields=[
                ('idTema',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('tema', models.TextField()),
            ],
            options={
                'ordering': ('tema', ),
            },
        ),
        migrations.CreateModel(
            name='VideoJuego',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('urlVideo', models.URLField()),
                ('juego',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='lowpricex_app.Juego')),
            ],
        ),
        migrations.AddField(
            model_name='juego',
            name='keywords',
            field=models.ManyToManyField(to='lowpricex_app.Keyword'),
        ),
        migrations.AddField(
            model_name='juego',
            name='plataforma',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='lowpricex_app.Plataforma'),
        ),
        migrations.AddField(
            model_name='juego',
            name='publishers',
            field=models.ManyToManyField(related_name='publishers',
                                         to='lowpricex_app.Empresa'),
        ),
        migrations.AddField(
            model_name='juego',
            name='temas',
            field=models.ManyToManyField(to='lowpricex_app.Tema'),
        ),
        migrations.AddField(
            model_name='imagenjuego',
            name='juego',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='lowpricex_app.Juego'),
        ),
        migrations.AddField(
            model_name='historicojuego',
            name='juego',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='lowpricex_app.Juego'),
        ),
    ]
Esempio n. 22
0
class FlowcellSummaryBarcode(models.Model):
    """
    :purpose: Summarise information from runs by flowcell, barcode name, fastq read type, and status (pass or fail).
     There is one record per flowcell. Most of the charts in the flowcell page use this data.
    Fields:
    :flowcell: (Flowcell) Foreign key to Flowcell
    :read_type_name: (FastReadType) FastqReadType name
    :barcode_name: (Barcode) Barcode name
    ;rejection_status: (Barcode) Foreign key to whether the read was accepted or unblocked
    :status: (boolean) Pass or Fail; originates from FastqRead is_pass attribute
    :quality_sum: (float) # TODO
    :read_count: (float) Total number of all reads from all runs of the flowcell
    :total_length: (float) Sum of the length of all reads from all runs of the flowcell
    :max_length: (float) Maximum read length of the flowcell
    :min_length: (float) Minimum read length of the flowcell
    :channel_presence: (str) Sequence of 3000 zeros and ones representing the presence or absence of a strand
    :channel_count: (int) Retuns the sum of ones in the channel_presence
    """

    flowcell = models.ForeignKey(
        Flowcell, on_delete=models.CASCADE, related_name="flowcellsummariesbarcodes"
    )
    read_type_name = models.CharField(max_length=32)
    barcode_name = models.CharField(max_length=32)
    rejection_status = models.CharField(
        max_length=32, default="Sequenced", null=True, blank=True,
    )
    status = models.CharField(max_length=32)
    quality_sum = models.DecimalField(decimal_places=2, max_digits=12, default=0)
    read_count = models.IntegerField(default=0)
    total_length = models.BigIntegerField(default=0)
    max_length = models.IntegerField(default=0)
    min_length = models.IntegerField(default=0)
    channel_presence = models.CharField(max_length=3000, default="0" * 3000)
    channel_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Flowcell Summary"
        verbose_name_plural = "Flowcell Summary"
        db_table = "flowcell_summary_barcode"
        constraints = [
            models.UniqueConstraint(
                fields=[
                    "flowcell",
                    "barcode_name",
                    "rejection_status",
                    "read_type_name",
                    "status",
                ],
                name="flowcell_summ",
            )
        ]

    def __str__(self):
        return "{} {} {} {} {}".format(
            self.flowcell,
            self.total_length,
            self.read_count,
            self.read_type_name,
            self.barcode_name,
        )

    def average_read_length(self):
        """
        TODO
        """
        if self.read_count > 0:
            return self.total_length / self.read_count
        else:
            return 0

    def number_active_channels(self):
        """
        TODO
        """
        return len(self.channel_presence.replace("0", ""))
Esempio n. 23
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('customers', '0001_initial'),
        ('lodging', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='City',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name_ascii',
                 models.CharField(blank=True, db_index=True, max_length=200)),
                ('slug',
                 autoslug.fields.AutoSlugField(editable=False,
                                               populate_from='name_ascii')),
                ('geoname_id',
                 models.IntegerField(blank=True, null=True, unique=True)),
                ('alternate_names',
                 models.TextField(blank=True, default='', null=True)),
                ('name', models.CharField(db_index=True, max_length=200)),
                ('display_name', models.CharField(max_length=200)),
                ('search_names',
                 cities_light.abstract_models.ToSearchTextField(
                     blank=True, db_index=True, default='', max_length=4000)),
                ('latitude',
                 models.DecimalField(blank=True,
                                     decimal_places=5,
                                     max_digits=8,
                                     null=True)),
                ('longitude',
                 models.DecimalField(blank=True,
                                     decimal_places=5,
                                     max_digits=8,
                                     null=True)),
                ('population',
                 models.BigIntegerField(blank=True, db_index=True, null=True)),
                ('feature_code',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=10,
                                  null=True)),
                ('timezone', models.CharField(max_length=40)),
            ],
            options={
                'verbose_name': 'Ciudad',
                'verbose_name_plural': 'Ciudades',
            },
        ),
        migrations.CreateModel(
            name='Country',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name_ascii',
                 models.CharField(blank=True, db_index=True, max_length=200)),
                ('slug',
                 autoslug.fields.AutoSlugField(editable=False,
                                               populate_from='name_ascii')),
                ('geoname_id',
                 models.IntegerField(blank=True, null=True, unique=True)),
                ('alternate_names',
                 models.TextField(blank=True, default='', null=True)),
                ('name', models.CharField(max_length=200, unique=True)),
                ('code2',
                 models.CharField(blank=True,
                                  max_length=2,
                                  null=True,
                                  unique=True)),
                ('code3',
                 models.CharField(blank=True,
                                  max_length=3,
                                  null=True,
                                  unique=True)),
                ('continent',
                 models.CharField(choices=[('OC', 'Oceania'), ('EU', 'Europe'),
                                           ('AF', 'Africa'),
                                           ('NA', 'North America'),
                                           ('AN', 'Antarctica'),
                                           ('SA', 'South America'),
                                           ('AS', 'Asia')],
                                  db_index=True,
                                  max_length=2)),
                ('tld',
                 models.CharField(blank=True, db_index=True, max_length=5)),
                ('phone', models.CharField(blank=True,
                                           max_length=20,
                                           null=True)),
            ],
            options={
                'verbose_name': 'Pais',
                'verbose_name_plural': 'Paises',
            },
        ),
        migrations.CreateModel(
            name='Location',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('zip_code',
                 models.CharField(blank=True, max_length=255, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Region',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name_ascii',
                 models.CharField(blank=True, db_index=True, max_length=200)),
                ('slug',
                 autoslug.fields.AutoSlugField(editable=False,
                                               populate_from='name_ascii')),
                ('geoname_id',
                 models.IntegerField(blank=True, null=True, unique=True)),
                ('alternate_names',
                 models.TextField(blank=True, default='', null=True)),
                ('name', models.CharField(db_index=True, max_length=200)),
                ('display_name', models.CharField(max_length=200)),
                ('geoname_code',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=50,
                                  null=True)),
                ('country',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='location.Country')),
            ],
            options={
                'verbose_name': 'Region',
                'verbose_name_plural': 'Regiones',
            },
        ),
        migrations.CreateModel(
            name='CustomerLocation',
            fields=[
                ('location_ptr',
                 models.OneToOneField(
                     auto_created=True,
                     on_delete=django.db.models.deletion.CASCADE,
                     parent_link=True,
                     primary_key=True,
                     serialize=False,
                     to='location.Location')),
                ('sort_order',
                 models.IntegerField(blank=True, editable=False, null=True)),
                ('lodging',
                 modelcluster.fields.ParentalKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='customer_location',
                     to='customers.Customer')),
            ],
            options={
                'ordering': ['sort_order'],
                'abstract': False,
            },
            bases=('location.location', models.Model),
        ),
        migrations.CreateModel(
            name='LodgingLocation',
            fields=[
                ('location_ptr',
                 models.OneToOneField(
                     auto_created=True,
                     on_delete=django.db.models.deletion.CASCADE,
                     parent_link=True,
                     primary_key=True,
                     serialize=False,
                     to='location.Location')),
                ('sort_order',
                 models.IntegerField(blank=True, editable=False, null=True)),
                ('lodging',
                 modelcluster.fields.ParentalKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='lodging_location',
                     to='lodging.Lodging')),
            ],
            options={
                'ordering': ['sort_order'],
                'abstract': False,
            },
            bases=('location.location', models.Model),
        ),
        migrations.AddField(
            model_name='location',
            name='city',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='+',
                to='location.City',
                verbose_name='Ciudad'),
        ),
        migrations.AddField(
            model_name='location',
            name='country',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='+',
                to='location.Country',
                verbose_name='Pais'),
        ),
        migrations.AddField(
            model_name='location',
            name='region',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='+',
                to='location.Region',
                verbose_name='Region'),
        ),
        migrations.AddField(
            model_name='city',
            name='country',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='location.Country'),
        ),
        migrations.AddField(
            model_name='city',
            name='region',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to='location.Region'),
        ),
    ]
Esempio n. 24
0
class FastqRead(models.Model):
    """
    :purpose: Each read has a fastqread object. Contains the header information broken down, and some metadata about the read.
    Fields:
    :run: Foreign key linked to run object
    :read_id: The read ID
    :read: Read number auto incrementing in fastq header
    :channel: Channel number that the read was sequenced on
    :barcode: The barcode identifer/number if any
    :sequence_length:
    :quality_average:
    :is_pass: Whether the read passed QC or not
    :type: FK to fastqreadtype, example 1d^2
    :start_time:
    :created_date:
    :modified_Date:
    """

    run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name="reads")
    read_id = models.CharField(db_index=True, max_length=96)
    read = models.IntegerField(db_index=True)
    channel = models.IntegerField(db_index=True)
    barcode = models.ForeignKey(
        Barcode,
        # on_delete=models.CASCADE,
        related_name="reads",
        null=True,
        on_delete=models.DO_NOTHING,
    )
    rejected_barcode = models.ForeignKey(
        Barcode,
        on_delete=models.DO_NOTHING,
        related_name="rejection_status",
        null=True,
        blank=True,
    )
    barcode_name = models.CharField(db_index=True, max_length=32,)
    sequence_length = models.BigIntegerField(null=True, blank=True, db_index=True)
    quality_average = models.DecimalField(
        decimal_places=2, max_digits=5, null=True, blank=True
    )
    is_pass = models.BooleanField()  # pass = true, fail = false
    type = models.ForeignKey(FastqReadType, on_delete=models.DO_NOTHING,)
    start_time = models.DateTimeField(db_index=True)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    fastqfile = models.ForeignKey(
        FastqFile, on_delete=models.CASCADE, related_name="reads", null=True,
    )
    sequence = models.TextField(blank=True, null=True)

    quality = models.TextField(blank=True, null=True,)
    flowcell = models.ForeignKey(
        Flowcell, on_delete=models.CASCADE, null=True, blank=True,
    )

    class Meta:
        verbose_name = "FASTQ Read"
        verbose_name_plural = "FASTQ Read"

    def __str__(self):
        # return "1"
        return str(self.read_id)
Esempio n. 25
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='agriculture',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('geometry',
                 django.contrib.gis.db.models.fields.PolygonField(srid=4326)),
                ('name', models.CharField(max_length=20)),
                ('location',
                 django.contrib.gis.db.models.fields.PointField(blank=True,
                                                                max_length=30,
                                                                srid=4326)),
                ('Additionalinfo', models.CharField(blank=True,
                                                    max_length=20)),
                ('Type', models.CharField(max_length=20)),
            ],
        ),
        migrations.CreateModel(
            name='districts',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('ddgn', models.BigIntegerField()),
                ('first_dcod', models.IntegerField()),
                ('first_dist', models.CharField(max_length=50)),
                ('first_gn_c', models.FloatField()),
                ('first_stat', models.IntegerField()),
                ('shape_leng', models.FloatField()),
                ('shape_area', models.FloatField()),
                ('area', models.FloatField()),
                ('centroid_x', models.FloatField()),
                ('centroid_y', models.FloatField()),
                ('geom',
                 django.contrib.gis.db.models.fields.MultiPolygonField(
                     srid=4326)),
            ],
        ),
        migrations.CreateModel(
            name='newflood',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('geometry',
                 django.contrib.gis.db.models.fields.PolygonField(srid=4326)),
            ],
        ),
        migrations.CreateModel(
            name='pointofinterests',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
                ('lat', models.FloatField()),
                ('lon', models.FloatField()),
                ('alt', models.FloatField()),
            ],
        ),
    ]
Esempio n. 26
0
class Pay(models.Model):
    amount = models.FloatField()
    reference = models.BigIntegerField(unique=True, null=True, default=None)
    confirmed = models.BooleanField(default=False)
Esempio n. 27
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Category',
            fields=[
                ('cat_id', models.AutoField(primary_key=True,
                                            serialize=False)),
                ('cat_title', models.CharField(max_length=255, unique=True)),
                ('cat_pages', models.IntegerField()),
                ('cat_subcats', models.IntegerField()),
                ('cat_files', models.IntegerField()),
            ],
            options={
                'managed': False,
                'db_table': 'category',
            },
        ),
        migrations.CreateModel(
            name='Categorylinks',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('cl_from', models.IntegerField()),
                ('cl_to', models.CharField(max_length=255)),
                ('cl_sortkey', models.CharField(max_length=230)),
                ('cl_timestamp', models.DateTimeField()),
                ('cl_sortkey_prefix', models.CharField(max_length=255)),
                ('cl_collation', models.CharField(max_length=32)),
                ('cl_type', models.CharField(max_length=6)),
            ],
            options={
                'managed': False,
                'db_table': 'categorylinks',
            },
        ),
        migrations.CreateModel(
            name='Page',
            fields=[
                ('page_id', models.AutoField(primary_key=True,
                                             serialize=False)),
                ('page_namespace', models.IntegerField()),
                ('page_title', models.CharField(max_length=255)),
                ('page_restrictions', models.TextField()),
                ('page_counter', models.BigIntegerField()),
                ('page_is_redirect', models.IntegerField()),
                ('page_is_new', models.IntegerField()),
                ('page_random', models.FloatField()),
                ('page_touched', models.CharField(max_length=14)),
                ('page_links_updated',
                 models.CharField(blank=True, max_length=14, null=True)),
                ('page_latest', models.IntegerField()),
                ('page_len', models.IntegerField()),
                ('page_content_model',
                 models.CharField(blank=True, max_length=32, null=True)),
                ('page_lang',
                 models.CharField(blank=True, max_length=35, null=True)),
            ],
            options={
                'managed': False,
                'db_table': 'page',
            },
        ),
        migrations.CreateModel(
            name='Pagelinks',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('pl_from', models.IntegerField()),
                ('pl_namespace', models.IntegerField()),
                ('pl_title', models.CharField(max_length=255)),
                ('pl_from_namespace', models.IntegerField()),
            ],
            options={
                'managed': False,
                'db_table': 'pagelinks',
            },
        ),
        migrations.CreateModel(
            name='Redirect',
            fields=[
                ('rd_from',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('rd_namespace', models.IntegerField()),
                ('rd_title', models.CharField(max_length=255)),
                ('rd_interwiki',
                 models.CharField(blank=True, max_length=32, null=True)),
                ('rd_fragment',
                 models.CharField(blank=True, max_length=255, null=True)),
            ],
            options={
                'managed': False,
                'db_table': 'redirect',
            },
        ),
        migrations.CreateModel(
            name='Hypernym',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('key', models.CharField(db_index=True, max_length=255)),
                ('value', models.TextField()),
            ],
        ),
    ]
Esempio n. 28
0
class ArtifactCraftInstance(ArtifactCraft):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    owner = models.ForeignKey(Summoner, on_delete=models.CASCADE)
    com2us_id = models.BigIntegerField(blank=True, null=True)
    quantity = models.IntegerField(default=1)
Esempio n. 29
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='CbObjects',
            fields=[
                ('id',
                 models.CharField(max_length=64,
                                  primary_key=True,
                                  serialize=False)),
                ('entity_type', models.CharField(max_length=16)),
                ('entity_id', models.BigIntegerField()),
                ('parent_id',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('name', models.CharField(max_length=255)),
                ('normalized_name', models.CharField(max_length=255)),
                ('permalink', models.CharField(max_length=255)),
                ('category_code',
                 models.CharField(blank=True, max_length=32, null=True)),
                ('status',
                 models.CharField(blank=True, max_length=32, null=True)),
                ('founded_at', models.DateField(blank=True, null=True)),
                ('closed_at', models.DateField(blank=True, null=True)),
                ('domain',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('homepage_url',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('twitter_username',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('logo_url',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('logo_width', models.IntegerField(blank=True, null=True)),
                ('logo_height', models.IntegerField(blank=True, null=True)),
                ('short_description',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('description',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('overview', models.TextField(blank=True, null=True)),
                ('tag_list',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('country_code',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('state_code',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('city', models.CharField(blank=True, max_length=64,
                                          null=True)),
                ('region',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('first_investment_at', models.DateField(blank=True,
                                                         null=True)),
                ('last_investment_at', models.DateField(blank=True,
                                                        null=True)),
                ('investment_rounds', models.IntegerField(blank=True,
                                                          null=True)),
                ('invested_companies',
                 models.IntegerField(blank=True, null=True)),
                ('first_funding_at', models.DateField(blank=True, null=True)),
                ('last_funding_at', models.DateField(blank=True, null=True)),
                ('funding_rounds', models.IntegerField(blank=True, null=True)),
                ('funding_total_usd',
                 models.DecimalField(blank=True,
                                     decimal_places=0,
                                     max_digits=15,
                                     null=True)),
                ('first_milestone_at', models.DateField(blank=True,
                                                        null=True)),
                ('last_milestone_at', models.DateField(blank=True, null=True)),
                ('milestones', models.IntegerField(blank=True, null=True)),
                ('relationships', models.IntegerField(blank=True, null=True)),
                ('created_by',
                 models.CharField(blank=True, max_length=64, null=True)),
                ('created_at', models.DateTimeField(blank=True, null=True)),
                ('updated_at', models.DateTimeField(blank=True, null=True)),
            ],
            options={
                'db_table': 'cb_objects',
                'managed': False,
            },
        ),
    ]
Esempio n. 30
0
class Migration(migrations.Migration):

    dependencies = [
        ('items', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='ComposeItem',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('outer_id',
                 models.CharField(
                     db_index=True,
                     max_length=64,
                     verbose_name=
                     '\u7ec4\u5408\u5546\u54c1\u5916\u90e8\u7f16\u7801',
                     blank=True)),
                ('outer_sku_id',
                 models.CharField(
                     db_index=True,
                     max_length=64,
                     verbose_name=
                     '\u7ec4\u5408\u5546\u54c1\u89c4\u683c\u7f16\u7801',
                     blank=True)),
                ('num',
                 models.IntegerField(default=1,
                                     verbose_name='\u5546\u54c1\u6570\u91cf')),
                ('extra_info',
                 models.TextField(verbose_name='\u4fe1\u606f', blank=True)),
                ('created', models.DateTimeField(auto_now_add=True,
                                                 null=True)),
                ('modified', models.DateTimeField(auto_now=True, null=True)),
            ],
            options={
                'db_table':
                'shop_memorule_composeitem',
                'verbose_name':
                '\u62c6\u5206\u89c4\u5219\u5546\u54c1',
                'verbose_name_plural':
                '\u62c6\u5206\u89c4\u5219\u5546\u54c1\u5217\u8868',
            },
        ),
        migrations.CreateModel(
            name='ComposeRule',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('outer_id',
                 models.CharField(
                     db_index=True,
                     max_length=64,
                     verbose_name='\u5546\u54c1\u5916\u90e8\u7f16\u7801',
                     blank=True)),
                ('outer_sku_id',
                 models.CharField(
                     db_index=True,
                     max_length=64,
                     verbose_name='\u5546\u54c1\u89c4\u683c\u7f16\u7801',
                     blank=True)),
                ('seller_id',
                 models.IntegerField(default=0,
                                     verbose_name='\u5356\u5bb6ID')),
                ('payment',
                 models.IntegerField(default=0,
                                     null=True,
                                     verbose_name='\u91d1\u989d')),
                ('type',
                 models.CharField(
                     max_length=10,
                     verbose_name='\u89c4\u5219\u7c7b\u578b',
                     choices=[
                         (b'payment', b'\xe6\xbb\xa1\xe5\xb0\xb1\xe9\x80\x81'),
                         (b'product',
                          b'\xe7\xbb\x84\xe5\x90\x88\xe6\x8b\x86\xe5\x88\x86'),
                         (b'gifts', b'\xe4\xb9\xb0\xe5\xb0\xb1\xe9\x80\x81')
                     ])),
                ('gif_count',
                 models.IntegerField(default=0,
                                     verbose_name='\u5269\u4f59\u540d\u989d')),
                ('scb_count',
                 models.IntegerField(default=0,
                                     verbose_name='\u5df2\u9001\u540d\u989d')),
                ('extra_info',
                 models.TextField(verbose_name='\u4fe1\u606f', blank=True)),
                ('start_time',
                 models.DateTimeField(null=True,
                                      verbose_name='\u5f00\u59cb\u65f6\u95f4',
                                      blank=True)),
                ('end_time',
                 models.DateTimeField(null=True,
                                      verbose_name='\u7ed3\u675f\u65f6\u95f4',
                                      blank=True)),
                ('created',
                 models.DateTimeField(auto_now_add=True,
                                      verbose_name='\u521b\u5efa\u65f6\u95f4',
                                      null=True)),
                ('modified',
                 models.DateTimeField(auto_now=True,
                                      verbose_name='\u4fee\u6539\u65f6\u95f4',
                                      null=True)),
                ('status',
                 models.BooleanField(default=False,
                                     verbose_name='\u751f\u6548')),
            ],
            options={
                'db_table': 'shop_memorule_composerule',
                'verbose_name': '\u5339\u914d\u89c4\u5219',
                'verbose_name_plural': '\u62c6\u5206\u89c4\u5219\u5217\u8868',
            },
        ),
        migrations.CreateModel(
            name='InterceptTrade',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('buyer_nick',
                 models.CharField(db_index=True,
                                  max_length=64,
                                  verbose_name='\u4e70\u5bb6\u6635\u79f0',
                                  blank=True)),
                ('buyer_mobile',
                 models.CharField(db_index=True,
                                  max_length=24,
                                  verbose_name='\u624b\u673a',
                                  blank=True)),
                ('serial_no',
                 models.CharField(db_index=True,
                                  max_length=64,
                                  verbose_name='\u5916\u90e8\u5355\u53f7',
                                  blank=True)),
                ('trade_id',
                 models.BigIntegerField(
                     null=True,
                     verbose_name='\u7cfb\u7edf\u8ba2\u5355ID',
                     blank=True)),
                ('modified',
                 models.DateTimeField(auto_now=True,
                                      verbose_name='\u4fee\u6539\u65f6\u95f4',
                                      null=True)),
                ('created',
                 models.DateTimeField(auto_now_add=True,
                                      verbose_name='\u521b\u5efa\u65e5\u671f',
                                      null=True)),
                ('status',
                 models.IntegerField(default=0,
                                     verbose_name='\u72b6\u6001',
                                     choices=[(0, '\u672a\u62e6\u622a'),
                                              (1, '\u5df2\u62e6\u622a')])),
            ],
            options={
                'db_table': 'shop_intercept_trade',
                'verbose_name': '\u62e6\u622a\u8ba2\u5355',
                'verbose_name_plural': '\u62e6\u622a\u8ba2\u5355\u5217\u8868',
            },
        ),
        migrations.CreateModel(
            name='ProductRuleField',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('outer_id', models.CharField(max_length=64, db_index=True)),
                ('custom_alias', models.CharField(max_length=256, blank=True)),
                ('custom_default', models.TextField(max_length=256,
                                                    blank=True)),
            ],
            options={
                'db_table': 'shop_memorule_productrulefield',
                'verbose_name': '\u5f85\u5ba1\u6838\u89c4\u5219',
            },
        ),
        migrations.CreateModel(
            name='RuleFieldType',
            fields=[
                ('field_name',
                 models.CharField(max_length=64,
                                  serialize=False,
                                  primary_key=True)),
                ('field_type',
                 models.CharField(max_length=10,
                                  choices=[
                                      (b'single', b'\xe5\x8d\x95\xe9\x80\x89'),
                                      (b'check', b'\xe5\xa4\x8d\xe9\x80\x89'),
                                      (b'text', b'\xe6\x96\x87\xe6\x9c\xac')
                                  ])),
                ('alias', models.CharField(max_length=64)),
                ('default_value', models.TextField(max_length=256,
                                                   blank=True)),
            ],
            options={
                'db_table': 'shop_memorule_rulefieldtype',
            },
        ),
        migrations.CreateModel(
            name='RuleMemo',
            fields=[
                ('tid',
                 models.BigIntegerField(serialize=False, primary_key=True)),
                ('is_used', models.BooleanField(default=False)),
                ('rule_memo', models.TextField(max_length=1000, blank=True)),
                ('seller_flag', models.IntegerField(null=True)),
                ('created', models.DateTimeField(auto_now_add=True,
                                                 null=True)),
                ('modified', models.DateTimeField(auto_now=True, null=True)),
            ],
            options={
                'db_table': 'shop_memorule_rulememo',
            },
        ),
        migrations.CreateModel(
            name='TradeRule',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('formula', models.CharField(max_length=64, blank=True)),
                ('memo', models.CharField(max_length=64, blank=True)),
                ('formula_desc', models.TextField(max_length=256, blank=True)),
                ('scope',
                 models.CharField(
                     max_length=10,
                     choices=[
                         (b'trade', b'\xe4\xba\xa4\xe6\x98\x93\xe5\x9f\x9f'),
                         (b'product', b'\xe5\x95\x86\xe5\x93\x81\xe5\x9f\x9f')
                     ])),
                ('status',
                 models.CharField(max_length=2,
                                  choices=[
                                      (b'US', b'\xe4\xbd\xbf\xe7\x94\xa8'),
                                      (b'SX', b'\xe5\xa4\xb1\xe6\x95\x88')
                                  ])),
                ('items',
                 models.ManyToManyField(related_name='rules',
                                        db_table=b'shop_memorule_itemrulemap',
                                        to='items.Item')),
            ],
            options={
                'db_table': 'shop_memorule_traderule',
            },
        ),
        migrations.AddField(
            model_name='productrulefield',
            name='field',
            field=models.ForeignKey(to='memorule.RuleFieldType'),
        ),
        migrations.AlterUniqueTogether(
            name='composerule',
            unique_together=set([('outer_id', 'outer_sku_id', 'type')]),
        ),
        migrations.AddField(
            model_name='composeitem',
            name='compose_rule',
            field=models.ForeignKey(related_name='compose_items',
                                    verbose_name='\u5546\u54c1\u89c4\u5219',
                                    to='memorule.ComposeRule'),
        ),
    ]