Exemplo n.º 1
0
class Record(models.Model):
    """
    Uploaded Record
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    uploaded_at = models.DateTimeField(default=timezone.now)

    entry = models.CharField(max_length=100, blank=True)
    args = mysql_models.JSONField(null=True, blank=True)
    working_dir = models.CharField(max_length=50, blank=True)

    git_user = models.CharField(max_length=50)
    git_repo = models.CharField(max_length=50)
    git_commit = models.CharField(max_length=40)

    record_information = mysql_models.JSONField(null=True, blank=True)

    result = mysql_models.JSONField()

    description = models.CharField(max_length=1000, blank=True)

    hidden = models.BooleanField(default=False)

    def __str__(self):
        return self.github_str

    @property
    def github_url(self):
        return 'https://github.com/{}/{}/tree/{}'.format(
            self.git_user, self.git_repo, self.git_commit)

    @property
    def github_str(self):
        return '{}/{}@{}'.format(self.git_user, self.git_repo,
                                 self.git_commit[:6])
Exemplo n.º 2
0
class Expressions(models.Model):
    domain = models.CharField('domain', max_length=15, null=True)
    expression = models.TextField('expression',
                                  default='',
                                  blank=True,
                                  null=True)
    intents = dmysql.JSONField('intents', default=list, blank=True, null=True)
    cumulative_cause_intents = dmysql.JSONField('cumulative cause intents',
                                                default=list,
                                                blank=True,
                                                null=True)
    cumulative_effect_intents = dmysql.JSONField('cumulative effect intents',
                                                 default=list,
                                                 blank=True,
                                                 null=True)
    datecreated = models.DateTimeField(auto_now_add=True,
                                       blank=True,
                                       null=True)

    class Meta:
        indexes = [
            models.Index(fields=[
                'domain',
            ]),
        ]

    def __str__(self):
        return '{}'.format(self.id)
Exemplo n.º 3
0
class LaundryShop(models.Model):
    STATUS_CHOICES = (('0', 'close'), ('1', 'open'), ('9', 'disable'))
    profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    tel = models.CharField(max_length=11)
    information = models.TextField()
    operating_time = mysql_models.JSONField()
    """
    {
        {
            "days": ["월", "화", "수"],
            "start_time": "09:30",
            "end_time": "20:30"
        },
        {
            "days": ["주말"],
            "start_time": "10:30",
            "end_time": "18:30"
        }
    }
    """
    min_price = models.PositiveIntegerField()
    grade = models.DecimalField(max_digits=2, decimal_places=1, default=0)
    delivery_dt = models.CharField(max_length=20)
    like_num = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=2,
                              choices=STATUS_CHOICES,
                              default='0')

    def __str__(self):
        return self.name
Exemplo n.º 4
0
class Review(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    from order.models import Order
    order = models.OneToOneField(Order,
                                 null=True,
                                 blank=True,
                                 on_delete=models.CASCADE)
    laundryshop = models.ForeignKey(LaundryShop, on_delete=models.CASCADE)
    parent = models.OneToOneField('self',
                                  null=True,
                                  blank=True,
                                  related_name='comment',
                                  on_delete=models.CASCADE)
    content = models.TextField()
    grade = models.SmallIntegerField(null=True, blank=True)
    image = mysql_models.JSONField(null=True, blank=True)
    """
    {
        "imageUrls": ["이미지주소1", "이미지주소2", ... ]
    }
    """
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    def __str__(self):
        return self.content[:10]
Exemplo n.º 5
0
class CharacterTemplate(Model):
    class Meta:
        db_table = 'mmo_character_template'
        unique_together = ('race', 'character_class')

    race = CharField(max_length=6, choices=Race.choices())
    character_class = CharField(max_length=8, choices=CharacterClass.choices())
    animations = mysql_models.JSONField()
    sprite_sheet = CharField(max_length=32)
Exemplo n.º 6
0
class RolesInfo(model0.Model):
    """角色:绑定权限"""

    name = model0.CharField(max_length=64,
                            null=True,
                            blank=True,
                            verbose_name='角色名称')
    desc = model0.TextField(max_length=300,
                            null=True,
                            blank=True,
                            verbose_name='角色描述')
    status = model0.SmallIntegerField(choices=settings.STATUS_USE_CHOICE,
                                      default=1,
                                      null=True,
                                      verbose_name='是否启用')
    level = model0.SmallIntegerField(choices=settings.DATA_LEVEL_CHOICE,
                                     default=3,
                                     null=True,
                                     verbose_name='数据级别')
    menu_list = model1.JSONField(null=True, blank=True, verbose_name='菜单权限')

    creator = model0.ForeignKey(to='UsersInfo',
                                related_name='roles_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='UsersInfo',
                                 related_name='roles_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'systems'
        db_table = 's_roles'
        verbose_name = '角色'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
Exemplo n.º 7
0
class FormQuestion(models57.Model):
    """
    Model to store all form questions(fields) irrespective of order or conditions.
    Thus, this model provides flat list of all fields used in the form.

    Moreover, it also keeps a track of previous fields that have been either updated or removed.
    But this model cannot be used as audit trail since, it overrides fields to latest configurations
    if its label & data type class has not been changed.

    **Uniqueness:**

        ``form_id``, ``label``, ``field_class``

    **Logic**:

        - Before inserting new record, table it looked up form any previous record with
          key consisting of (form_id, label, field_class).
        - If found, this record is updated with new configurations settings.
        - If not found, new entry is made. Old one automatically get obsolete as there
          is new record with latest form_version.

    **Points**:

        - To obtains list of all fields currently present in the form, query with
          key (``form_id``, ``form_version``)
        - To obtains list of all fields that are or were in the form, query with
          ``form_id``.

    **Authors**: Gagandeep Singh
    """

    form        = models.ForeignKey(Form, db_index=True, help_text='Form to which this question field belongs to')
    form_version = models.UUIDField(default=uuid.uuid4, db_index=True, help_text='Form version to which this version of field belongs.')
    label       = models.CharField(max_length=255, help_text='Label of the form field.')
    field_class = models.CharField(max_length=128, help_text='Field class of this question.  This must be exactly same as the field class name.')
    text_translation_id = models.CharField(max_length=128, help_text="Raw id of text translation :class:`languages.models.Translation`.")
    schema_json = models57.JSONField(help_text='Json schema of question field as per field class.')

    dated       = models.DateTimeField(db_index=True, help_text='Date on which this record was created/updated.')

    @property
    def translation(self):
        return Translation.objects.with_id(self.text_translation_id)

    class Meta:
        unique_together = ('form', 'label', 'field_class')
        ordering = ['form', 'dated']

    def __unicode__(self):
        return "{}: {}".format(self.form_id, self.label)
Exemplo n.º 8
0
class CustomsFundsInfo(model0.Model):
    """清关款项 模型类"""

    type = model0.SmallIntegerField(choices=settings.CUSTOMS_LEVEL_CHOICE,
                                    default=1,
                                    verbose_name='类型')
    freight = model0.ForeignKey(to='business.FreightsInfo',
                                related_name='custom_funds',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属运单')
    fund_status = model0.SmallIntegerField(choices=settings.FUND_STATUS_CHOICE,
                                           default=1,
                                           verbose_name='款项状态')
    channel = model0.ForeignKey(to='systems.DataDictsValue',
                                related_name='custom_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属渠道')
    service = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='custom_funds_s',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='款项专员')
    y_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='应付金额')
    s_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='实付金额',
                                  default=0)
    j_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='减免金额',
                                  default=0)
    w_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='未结算金额')
    customs_fee = model0.FloatField(max_length=12,
                                    null=True,
                                    verbose_name='清关费',
                                    default=0)
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='减免说明')
    attachment_ids = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='附件列表')
    pack_time = model0.DateTimeField(null=True,
                                     blank=True,
                                     verbose_name="打包时间")

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='custom_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='custom_funds_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'funds'
        db_table = 'b_customs_funds'
        verbose_name = '货运款项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.freight.freight_code
Exemplo n.º 9
0
class BspTypeCustomization(models57.Model):
    """
    Model to customize a BSP type in terms of attributes for an organization.
    All BSPs have certain common attributes as well as attributes related to their type.
    However, it is possible that organization might want certain more attributes other than
    provided ones for their own use.

    This model allows organizations to define attributes and their data type.

    **Points**:

        - Only one customization can be defined for organization-BSP basis.
        - Data types for attributes are limited.

    **Authors**: Gagandeep Singh
    """

    # --- Classes ---
    class Attribute(JsonObject):
        """
        Attribute schema to define a custom bsp attribute.

        **Authors**: Gagandeep Singh
        """
        class ENUMS:
            DTYPE_INT = 'int'
            DTYPE_FLOAT = 'float'
            DTYPE_TEXT = 'text'
            DTYPE_BOOL = 'bool'
            CH_DTYPES = (
                (DTYPE_INT, 'Number'),
                (DTYPE_FLOAT, 'Decimal'),
                (DTYPE_TEXT, 'Text'),
                (DTYPE_BOOL, 'Boolean'),
            )

        _allow_dynamic_properties = False

        label = StringProperty(
            required=True, validators=[validate_label]
        )  # Lowercase label of the attribute. This is what value is stored against. Follow variable conventions.
        name = StringProperty(
            required=True)  # Name of the attribute. Free text.
        dtype = StringProperty(
            required=True,
            choices=ENUMS.CH_DTYPES)  # Data-type of the attribute

        # def __init__(self, _obj=None, **kwargs):
        #     super(BspTypeCustomization.Attribute, self).__init__(_obj=_obj, **kwargs)

    # --- Fields ---
    organization = models.ForeignKey(
        Organization,
        help_text='Organization for which this customization is defined.')
    bsp_type = models.CharField(max_length=64,
                                choices=BspTypes.choices,
                                help_text='BSP that is customized.')

    schema = models57.JSONField(
        validators=[validate_unique_label],
        help_text='Schema (list of objects) that defines custom attributes.')

    created_by = models.ForeignKey(
        User,
        editable=False,
        help_text='Person who created this customization.')
    created_on = models.DateTimeField(
        auto_now_add=True,
        editable=False,
        db_index=True,
        help_text='Date on which this record was created.')
    modified_on = models.DateTimeField(
        null=True,
        blank=True,
        editable=False,
        help_text='Date on which this record was modified.')

    class Meta:
        unique_together = ('organization', 'bsp_type')
        permissions = (('view_bsptypecustomization',
                        'Can be bsp type customizations'), )

    def __unicode__(self):
        return "{} - {}".format(self.bsp_type, self.organization.name)

    def get_attribute_schema(self, label):
        """
        Method to get attribute schema :class:`market.models.BspTypeCustomization.Attribute` given
        a label key.

        :param label: Label of the attribute to be searched
        :return: :class:`market.models.BspTypeCustomization.Attribute` instance or None if not found
        """
        for attr_dict in self.schema:
            if attr_dict['label'] == label:
                return BspTypeCustomization.Attribute(attr_dict)

        return None

    def get_attribute_labels_list(self):
        """
        Method to return all list of attribute labels.

        :return: List
        """
        list_labels = [attr['label'] for attr in self.schema]
        return list_labels

    def validate_data(self, data_dict):
        """
        Method to validate data dict as per the schema.

        :param data_dict: Dict if key-value data
        :return: (is_valid, error_msg) True if valid else False with error message
        """
        is_valid = True
        error_msg = None

        list_labels = self.get_attribute_labels_list()
        for label, value in data_dict.iteritems():
            if label not in list_labels:
                is_valid = False
                error_msg = "Invalid custom attribute '{}'. Allowed are {}.".format(
                    label, ','.join(list_labels))

        return (is_valid, error_msg)

    def clean(self):
        """
        Method to clean & validate data fields.

        **Authors**: Gagandeep Singh
        """
        # Validate schema
        if isinstance(self.schema, list):
            for attr in self.schema:
                try:
                    a_obj = BspTypeCustomization.Attribute(attr)
                except (BadValueError, WrappingAttributeError) as ex:
                    raise ValidationError("Schema error: {}".format(
                        ex.message))
        else:
            raise ValidationError('Schema must be a list.')

        # Check for reserved labels
        list_reserved_labels = BusinessServicePoint._fields.keys(
        ) + MAPPING_BSP_CLASS[self.bsp_type].properties().keys()
        for attr in self.schema:
            attr['label'] = attr['label'].lower(
            )  # Convert labels to lowercase

            if attr['label'] in list_reserved_labels:
                raise ValidationError("Label '{}' is reserved.".format(
                    attr['label']))

        if self.pk:
            self.modified_on = timezone.now()

        super(self.__class__, self).clean()

    def save(self, *args, **kwargs):
        """
        Pre-save method for this model.

        **Authors**: Gagandeep Singh
        """

        self.clean()
        super(self.__class__, self).save(*args, **kwargs)
Exemplo n.º 10
0
class Brand(models57.Model):
    """
    Model to store brand of an organization. A brand is any name, design, style, words or symbols used
    singularly or in combination that distinguish one product from another in the eyes of the customer.

    **Authors**: Gagandeep Singh
    """
    # --- Enums ---
    LOGO_DIM = (300, 100)
    LOGO_MAX_SIZE = 30 * 1024  # in bytes

    ICON_DIM = (64, 64)
    ICON_MAX_SIZE = 15 * 1024  # in bytes

    # --- Fields ---
    organization = models.ForeignKey(
        Organization,
        db_index=True,
        help_text='Organization to which this brand belongs to.')
    brand_uid = models.UUIDField(
        default=uuid.uuid4,
        unique=True,
        db_index=True,
        editable=False,
        help_text=
        'Unique ID of a brand which are hard to guess and can be used in urls. '
    )
    name = models.CharField(max_length=255,
                            unique=True,
                            db_index=True,
                            help_text='Name of the brand.')
    slug = models.SlugField(
        unique=True,
        blank=True,
        db_index=True,
        help_text=
        'Slug of the name used for url referencing and dedupe matching.')

    # Settings
    description = models.TextField(
        help_text='Short description about the brand.')
    logo = models.ImageField(max_length=512,
                             upload_to=upload_brand_logo_to,
                             help_text='Brand logo of size 300x100 pixels.')
    icon = models.ImageField(max_length=512,
                             upload_to=upload_brand_icon_to,
                             help_text='Brand icon of size 64x64 px.')

    # Customization
    ui_theme = models57.JSONField(
        default=None,
        blank=True,
        null=True,
        help_text=
        "Custom UI theme for this brand. This must be of format 'utilities.theme.UiTheme'"
    )
    theme_file = models.FileField(
        max_length=256,
        upload_to=upload_brand_theme_file_to,
        editable=False,
        help_text=
        'Theme file link which is automatically generated if ui_theme is defined'
    )

    # Status
    active = models.BooleanField(
        default=True,
        db_index=True,
        help_text='If false, it means brand is currenlty inactive.')

    # Misc
    created_by = models.ForeignKey(
        User,
        editable=False,
        related_name='created_by',
        help_text=
        'User that created this brand. This can be a staff or registered user.'
    )
    created_on = models.DateTimeField(
        auto_now_add=True,
        editable=False,
        db_index=True,
        help_text='Date on which this record was created.')
    modified_on = models.DateTimeField(
        null=True,
        blank=True,
        editable=False,
        help_text='Date on which this record was modified.')

    class Meta:
        ordering = ('name', )
        permissions = (("view_brand", "Can view brands"), )

    def __unicode__(self):
        return "{} ({})".format(self.name, self.organization.name)

    def update_theme_files(self, auto_save=True):
        """
        Method to update all theme files only if ui_theme is defined.

        :return: (bool) True if file was created and set to the field (irrespective of save), False if ui_theme was not set.

        **Authors**: Gagandeep Singh
        """
        if self.ui_theme:
            ui_theme = UiTheme(self.ui_theme)

            # render file
            content = render_skin(custom=True,
                                  clr_primary=ui_theme.primary,
                                  clr_prim_hover=ui_theme.primary_dark,
                                  clr_prim_disabled=ui_theme.primary_disabled)

            # Create InMemoryUploadObject
            f_io = StringIO.StringIO(content)
            mem_file_css = InMemoryUploadedFile(f_io, u'file', 'theme.css',
                                                u'text/css', f_io.len, None)

            self.theme_file = mem_file_css

            if auto_save:
                self.save()

            return True
        else:
            return False

    def clean(self):
        """
        Method to clean & validate data fields.

        **Authors**: Gagandeep Singh
        """

        if self.pk:
            # Update modified date
            self.modified_on = timezone.now()

        # Name slug
        if not self.slug:
            self.slug = slugify(self.name)

        # Images
        if not Brand.validate_logo_image(self.logo):
            raise ValidationError(
                'Logo must be {}x{} and less than {} KB.'.format(
                    Brand.LOGO_DIM[0], Brand.LOGO_DIM[1],
                    Brand.LOGO_MAX_SIZE / 1024))
        if not Brand.validate_icon_image(self.icon):
            raise ValidationError(
                'Icon must be {}x{} and less than {} KB.'.format(
                    Brand.ICON_DIM[0], Brand.ICON_DIM[1],
                    Brand.ICON_MAX_SIZE / 1024))

        # Check UI Theme
        if self.ui_theme is not None:
            if self.ui_theme == {}:
                self.ui_theme = None
            else:
                try:
                    theme_obj = UiTheme(self.ui_theme)
                except Exception as ex:
                    raise ValidationError("ui_theme: " + ex.message)

        super(self.__class__, self).clean()

    def save(self, update_theme=False, *args, **kwargs):
        """
        Pre-save method for this model.

        **Authors**: Gagandeep Singh
        """
        self.clean()

        # Update theme
        if update_theme:
            # Theme errors have been checked in clean()
            self.update_theme_files(auto_save=False)

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

    def delete(self, using=None, keep_parents=False):
        """
        Pre-delete method. (Not allowed)

        **Authors**: Gagandeep Singh
        """
        raise ValidationError(
            "You cannot delete a brand. Mark 'active' false instead.")

    # ----- Static methods -----
    @staticmethod
    def generate_uitheme(primary_color):
        """
        Method to generate ui theme json wrapper :class:`utilities.theme.UiTheme`.
        :param primary_color: Primary color in hex format
        :return: :class:`utilities.theme.UiTheme` instance
        """
        from utilities.theme import UiTheme, ColorUtils
        return UiTheme(
            primary=primary_color,
            primary_dark=ColorUtils.scale_hex_color(primary_color, -40),
            primary_disabled=ColorUtils.scale_hex_color(primary_color, 60))

    @staticmethod
    def does_exists(name):
        """
        Method to check if brand exists with given name or with slug of given name.

        :param name: Name of the brand
        :return: (bool) True if brand exists else False

        **Authors**: Gagandeep Singh
        """
        slug = slugify(name)
        return Brand.objects.filter(Q(name=name) | Q(slug=slug))

    @staticmethod
    def validate_logo_image(img_obj):
        """
        Method to validate brand logo image.
        Handles both ``InMemoryUploadedFile`` and ``ImageFieldFile`` objects.

        :param img_obj: InMemory object of image
        :return: True if image is valid

        **Authors**: Gagandeep Singh
        """
        if isinstance(img_obj, InMemoryUploadedFile):
            # InMemory object
            size = img_obj.size
            dim = Image.open(img_obj).size
        elif isinstance(img_obj, ImageFieldFile):
            # Django model field from ImageField
            size = img_obj._get_size()
            dim = img_obj._get_image_dimensions()

        return (size <= Brand.LOGO_MAX_SIZE and dim == Brand.LOGO_DIM)

    @staticmethod
    def validate_icon_image(img_obj):
        """
        Method to validate brand icon image.
        Handles both ``InMemoryUploadedFile`` and ``ImageFieldFile`` objects.

        :param img_obj: InMemory object of image
        :return: True if image is valid

        **Authors**: Gagandeep Singh
        """
        if isinstance(img_obj, InMemoryUploadedFile):
            # InMemory object
            size = img_obj.size
            dim = Image.open(img_obj).size
        elif isinstance(img_obj, ImageFieldFile):
            # Django model field from ImageField
            size = img_obj._get_size()
            dim = img_obj._get_image_dimensions()

        return (size <= Brand.ICON_MAX_SIZE and dim == Brand.ICON_DIM)
Exemplo n.º 11
0
class OrdFundsInfo(model0.Model):
    """订单款项 模型类"""

    order = model0.ForeignKey(to='business.OrdersInfo',
                              related_name='order_funds',
                              on_delete=model0.SET_NULL,
                              null=True,
                              blank=True,
                              db_constraint=False,
                              db_index=False,
                              verbose_name='所属订单')
    customer = model0.ForeignKey(to='customers.CustomersInfo',
                                 related_name='order_funds',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属客户')
    fund_status = model0.SmallIntegerField(choices=settings.FUND_STATUS_CHOICE,
                                           default=1,
                                           verbose_name='款项状态')
    order_status = model0.SmallIntegerField(
        choices=settings.ORDER_STATUS_CHOICE, default=1, verbose_name='订单状态')
    pay_type = model0.ForeignKey(to='systems.DataDictsValue',
                                 related_name='order_funds_p',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属付款类型')
    channel = model0.ForeignKey(to='systems.DataDictsValue',
                                related_name='order_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属渠道')
    service = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='order_funds_s',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='款项专员')
    price_w = model0.FloatField(max_length=12, null=True, verbose_name='价格重量')
    insurance_rate = model0.FloatField(max_length=12,
                                       null=True,
                                       verbose_name='保险费率',
                                       default=0)
    y_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='应收金额')
    s_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='实收金额',
                                  default=0)
    j_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='减免金额',
                                  default=0)
    w_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='未结算金额')
    freight_fee = model0.FloatField(max_length=12,
                                    null=True,
                                    verbose_name='运费')
    dispatch_fee = model0.FloatField(max_length=12,
                                     null=True,
                                     verbose_name='派送费',
                                     default=0)
    file_fee = model0.FloatField(max_length=12,
                                 null=True,
                                 verbose_name='文件费',
                                 default=0)
    operate_fee = model0.FloatField(max_length=12,
                                    null=True,
                                    verbose_name='操作费',
                                    default=0)
    insurance_fee = model0.FloatField(max_length=12,
                                      null=True,
                                      verbose_name='保险费',
                                      default=0)
    server_fee = model0.FloatField(max_length=12,
                                   null=True,
                                   verbose_name='服务费',
                                   default=0)
    insurance_money = model0.FloatField(max_length=12,
                                        null=True,
                                        verbose_name='保险金额',
                                        default=0)
    collection_money = model0.FloatField(max_length=12,
                                         null=True,
                                         verbose_name='代收金额')
    other_fee = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='其他费用',
                                  default=0)
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='减免说明')
    attachment_ids = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='附件列表')
    order_time = model0.DateTimeField(null=True, verbose_name="订单时间")

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='order_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='order_funds_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'funds'
        db_table = 'b_ord_funds'
        verbose_name = '订单款项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.order.trans_code
Exemplo n.º 12
0
class GraphDiagram(models57.Model):
    """
    Model to define a chart/graph diagram.

    **Points**:

        - Always use ``graph_uid`` for referencing.
        - ``form_id``: Is optional for feedback since feedback can have multiple forms. However, this is mandatory
          for other cases.

    **Authors**: Gagandeep Singh
    """
    # --- ENUMS ---
    CT_BSP_FEEDBACK = 'bsp_feedback'
    CH_CONTEXT = ((CT_BSP_FEEDBACK, 'BSP Feedback'), )

    graph_uid = models.UUIDField(default=uuid.uuid4,
                                 unique=True,
                                 db_index=True,
                                 editable=False,
                                 help_text='Unique ID for this graph diagram.')
    organization = models.ForeignKey(
        Organization,
        db_index=True,
        help_text='Organization to which this graph belongs.')
    context = models.CharField(
        max_length=32,
        choices=CH_CONTEXT,
        db_index=True,
        help_text='Context for which this graph is defined.')
    form = models.ForeignKey(
        'form_builder.Form',
        null=True,
        blank=True,
        db_index=True,
        help_text=
        'Form for which this graph is defined. Optional in case of feedback.')
    graph_type = models.CharField(max_length=32,
                                  choices=GraphCharts.choices_all,
                                  help_text='Type of graph.')

    title = models.CharField(max_length=1024,
                             help_text='User defined title of the graph.')
    description = tinymce_models.HTMLField(
        null=True, blank=True, help_text='Description about the graph.')

    graph_definition = models57.JSONField(
        help_text='Graph definition JSON as per graph definition classes.')
    pin_to_dashboard = models.BooleanField(
        default=False,
        db_index=True,
        help_text=
        'If True, this will be display on corresponding context dashboard.')

    # Misc
    created_by = models.ForeignKey(
        User,
        editable=False,
        help_text=
        'User that created this brand. This can be a staff or registered user.'
    )
    created_on = models.DateTimeField(
        auto_now_add=True,
        editable=False,
        db_index=True,
        help_text='Date on which this record was created.')
    modified_on = models.DateTimeField(
        null=True,
        blank=True,
        editable=False,
        help_text='Date on which this record was modified.')

    @property
    def graph(self):
        return GRAPH_CLASS_MAPPING[self.graph_type](self.graph_definition)

    def __unicode__(self):
        return "{} - {}".format(self.context, self.graph_type)

    def get_entity_model(self):
        """
        Method to return model class as per ``context`` field.

        :return: Model class

        **Authors**: Gagandeep Singh
        """
        if self.context == GraphDiagram.CT_BSP_FEEDBACK:
            return BspFeedbackResponse
        else:
            raise NotImplementedError(
                "'get_entity_model()' not implemented for '{}'.".format(
                    self.context))

    def get_data(self, data_filters={}, **kwargs):
        """
        Method to get data for this graph.

        :return: JSON data

        **Authors**: Gagandeep Singh
        """
        graph = self.graph
        entityModel = self.get_entity_model()

        final_filters = {}
        if self.organization_id:
            final_filters['organization_id'] = self.organization_id
        if self.form_id:
            final_filters["form_id"] = str(self.form_id)

        final_filters.update(data_filters)

        return graph.get_data(entityModel, final_filters, **kwargs)

    def clean(self):
        """
        Method to clean & validate data fields.

        **Authors**: Gagandeep Singh
        """

        if self.pk:
            # Update modified date
            self.modified_on = timezone.now()

        # Check form_id
        if self.context not in [GraphDiagram.CT_BSP_FEEDBACK
                                ] and self.form_id is None:
            raise ValidationError(
                "'form_id' is mandatory for '{}' graph diagram.".format(
                    self.context))

        # Check configuration as per type
        try:
            graph_definition = self.graph
        except (BadValueError, WrappingAttributeError) as ex:
            raise ValidationError(ex.message)

        super(self.__class__, self).clean()

    def save(self, *args, **kwargs):
        """
        Pre-save method for this model.

        **Authors**: Gagandeep Singh
        """
        self.clean()
        super(self.__class__, self).save(*args, **kwargs)
Exemplo n.º 13
0
class CustomersInfo(model0.Model):
    """ 客户模型类 """

    code = model0.CharField(max_length=32, null=True, verbose_name='客户代码')
    name = model0.CharField(max_length=100, null=True, verbose_name='客户名称')
    rank = model0.ForeignKey(to='systems.DataDictsValue',
                             related_name='customers',
                             on_delete=model0.SET_NULL,
                             null=True,
                             blank=True,
                             db_constraint=False,
                             db_index=False,
                             verbose_name='客户级别')
    salesman = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='customers_b',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='业务员')
    service = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='customers_s',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='客服专员')
    president_name = model0.CharField(max_length=64,
                                      null=True,
                                      verbose_name='客户方负责人')
    connect_ways = model0.CharField(max_length=32,
                                    null=True,
                                    verbose_name='联系方式')
    customer_address = model0.CharField(max_length=100,
                                        null=True,
                                        verbose_name='客户地址')
    manage_directions = model0.TextField(max_length=300,
                                         null=True,
                                         verbose_name='客户经营方向')
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      verbose_name='备注')
    attachment_ids = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='附件列表')

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='customers_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='customers_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'customers'
        db_table = 'i_customers'
        verbose_name = '客户方'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
Exemplo n.º 14
0
class Survey(models.Model):
    """
    Model to define a survey.

    **Points**:

        - Simple survey will not allow multiple survey phases.
        - Survey unique id is always attached with survey that can be shared to respondents. But only
          ``public`` and ``private`` survey are allowed to be answers.
        - Surveyor type:
            - **Organization**: Field ``organization`` is mandatory.
            - **Brand**: Field ``brand`` is mandatory.
            - **Individual**: ``created_by`` is used as surveyor.
        - Survey with audience as ``public`` is only visible to the public, rest are hidden.
        - Audience filer to automatically set to {} if audience type is ``self``.
        - Survey with status ``draft`` & ``paused`` are not visible to the public.

    **State chart diagram for survey status**:

        .. image:: ../../_static/surveys/survey_statechart.jpg


    **Authors**: Gagandeep Singh
    """

    # --- Enums ---
    SURVEY_UID_LEN = 8

    TYPE_SIMPLE = 'simple'
    TYPE_COMPLEX = 'complex'
    CH_TYPE = ((TYPE_SIMPLE, 'Simple'), (TYPE_COMPLEX, 'Complex'))

    OWNER_ORGANIZATION = 'organization'
    OWNER_INDIVIDUAL = 'individual'
    CH_OWNER = ((OWNER_ORGANIZATION, 'Organization'), (OWNER_INDIVIDUAL,
                                                       'Individual'))

    AUD_PUBLIC = 'public'
    AUD_UNLISTED = 'unlisted'
    AUD_SELF = 'self'
    CH_AUDIENCE = ((AUD_PUBLIC, 'Public'), (AUD_UNLISTED, 'Unlisted'),
                   (AUD_SELF, 'Self'))

    ST_DRAFT = 'draft'
    ST_READY = 'ready'
    ST_PAUSED = 'paused'
    ST_STOPPED = 'stopped'
    CH_STATUS = ((ST_DRAFT, 'Draft'), (ST_READY, 'Ready'),
                 (ST_PAUSED, 'Paused'), (ST_STOPPED, 'Stopped'))

    # --- Fields ---
    type = models.CharField(max_length=10,
                            default=None,
                            choices=CH_TYPE,
                            db_index=True,
                            help_text='Type of survey - simple or complex.')
    category = models.ForeignKey(SurveyCategory,
                                 help_text='Category of this survey.')

    # Basic
    survey_uid = models.CharField(
        max_length=SURVEY_UID_LEN,
        default=None,
        blank=True,
        editable=False,
        unique=True,
        db_index=True,
        help_text='Eight letter survey unique id that can be shared user users.'
    )
    title = models.CharField(
        max_length=512,
        default=None,
        db_index=True,
        help_text='Title of the survey. This is visible to the public')
    description = tinymce_models.HTMLField(
        default=None,
        help_text=
        'Detailed description about the survey. This tells what the survey is all about.'
    )

    tags = models.ManyToManyField(SurveyTag,
                                  default=None,
                                  blank=True,
                                  help_text='Tag survey with keywords.')
    start_date = models.DateField(
        help_text='Start date of this survey (Included).')
    end_date = models.DateField(
        help_text='End date of this survey (Included).')

    # Ownership
    ownership = models.CharField(
        max_length=16,
        choices=CH_OWNER,
        db_index=True,
        help_text='Who is conducting this survey? Organization/Individual?')
    organization = models.ForeignKey(
        Organization,
        null=True,
        blank=True,
        db_index=True,
        help_text=
        'Organization to which this survey belongs to if owner is an organization.'
    )
    brand = models.ForeignKey(
        Brand,
        null=True,
        blank=True,
        help_text=
        '(Optional) Tag a brand to this survey (only if owner is an organzation).'
    )

    # Audience
    audience_type = models.CharField(max_length=16,
                                     default=None,
                                     choices=CH_AUDIENCE,
                                     help_text='Type of the target audience.')
    audience_filters = models57.JSONField(
        default=None,
        blank=True,
        null=True,
        help_text=
        'Expression to filter the audience. (Only for public & invited)')

    # Status
    status = FSMField(default=ST_DRAFT,
                      choices=CH_STATUS,
                      protected=True,
                      help_text='Status of the survey')

    # Misc
    qrcode = models.ImageField(upload_to=upload_survey_qrcode_to,
                               blank=True,
                               editable=False,
                               help_text='Qrcode image file for this survey.')
    created_by = models.ForeignKey(
        User,
        editable=False,
        db_index=True,
        help_text=
        ':class:`django.contrib.auth.models.User` that created this survey.')
    created_on = models.DateTimeField(
        auto_now_add=True,
        editable=False,
        db_index=True,
        help_text='Date on which this record was created.')
    modified_on = models.DateTimeField(
        null=True,
        blank=True,
        editable=False,
        help_text='Date on which this record was modified.')

    @property
    def phases(self):
        return self.surveyphase_set.all().order_by('order')

    class Meta:
        permissions = (("view_survey", "Can view surveys"),
                       ("can_audit_response", "Can audit response"))

    def __unicode__(self):
        return self.title

    # --- Transitions ---
    @fsm_log_by
    @transition(field=status, source=ST_DRAFT, target=ST_READY)
    def trans_ready(self):
        """
        Transition edge to publish a survey. On publishing, survey is active & will automatically start
        as per ``start_date`` & ``end_date``.

        **Authors**: Gagandeep Singh
        """
        if not self.surveyphase_set.all().count():
            raise Exception("Denied! This survey must have atleast one phase.")

        if self.surveyphase_set.filter(form__is_ready=False).exists():
            raise Exception("Denied! Please complete your questionnaire(s).")

    @fsm_log_by
    @transition(field=status, source=ST_READY, target=ST_PAUSED)
    def trans_pause(self):
        """
        Transition edge to pause a survey after it has been published. Puases survey are not executable.
        This is used when user wants to halt a survey for sometime.

        **Authors**: Gagandeep Singh
        """
        pass

    @fsm_log_by
    @transition(field=status, source=ST_PAUSED, target=ST_READY)
    def trans_resume(self):
        """
        Transition edge to resume a paused survey. After resuming, it will be visible to public.

        **Authors**: Gagandeep Singh
        """
        if not self.surveyphase_set.all().count():
            raise Exception("Denied! This survey must have atleast one phase.")

        if self.surveyphase_set.filter(form__is_ready=False).exists():
            raise Exception("Denied! Please complete your questionnaire(s).")

    @fsm_log_by
    @transition(field=status, source=[ST_READY, ST_PAUSED], target=ST_STOPPED)
    def trans_stop(self):
        """
        Transition edge to stop a survey. A survey after stop cannot be restarted.

        **Authors**: Gagandeep Singh
        """
        pass

    # --- /Transitions ---

    def update_qrcode(self, auto_save=True):
        """
        Method to update survey qrcode.

        **Authors**: Gagandeep Singh
        """
        survey_uid = self.survey_uid
        if self.survey_uid is None:
            raise ValidationError("Survey uid is not set yet.")

        # Prepare data
        data = {
            "type": "survey",
            "survey_uid": survey_uid,
            "title": self.title
        }

        # Create qrcode image
        qr = qrcode.QRCode(
            version=3,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=2,
        )

        qr.add_data(data)
        qr.make(fit=True)

        img = qr.make_image()

        # Create image file
        img_io = StringIO.StringIO()
        img.save(img_io, format='JPEG')

        img_file = InMemoryUploadedFile(img_io, None,
                                        'qrcode_{}.jpg'.format(survey_uid),
                                        'image/jpeg', img_io.len, None)

        # Set file
        self.qrcode = img_file

        if auto_save:
            self.save()

    def has_gps_enabled(self):
        """
        Method to tell if this survey has any survey phase that has gps enabled.
        :return: True/False

        **Authors**: Gagandeep Singh
        """
        return Form.objects.filter(
            gps_enabled=True,
            id__in=SurveyPhase.objects.filter(survey_id=self.id).values_list(
                'form', flat=True)).exists()

    def clean(self):
        """
        Method to clean & validate data fields.

        **Authors**: Gagandeep Singh
        """

        if not self.pk:
            # Set, check & correct survey_uid
            self.survey_uid = Survey.generate_uid()

            # Set qrcode
            self.update_qrcode(auto_save=False)

        # Check surveyor type
        if self.ownership == Survey.OWNER_ORGANIZATION:
            if self.organization is None:
                raise ValidationError(
                    "Organization required since survey owner is an organization."
                )
        elif self.ownership == Survey.OWNER_INDIVIDUAL:
            if self.type != Survey.TYPE_SIMPLE:
                raise ValidationError(
                    "Only simple surveys are allowed for individuals.")
        else:
            ValidationError("Invalid surveyor type '{}'.".format(
                self.ownership))

        # Check & correct audience type
        if self.audience_type == Survey.AUD_SELF:
            self.audience_filters = {}

        if self.pk:
            # Update modified date
            self.modified_on = timezone.now()

        super(self.__class__, self).clean()

    def save(self, *args, **kwargs):
        """
        Pre-save method for this model.

        **Authors**: Gagandeep Singh
        """

        self.clean()
        super(self.__class__, self).save(*args, **kwargs)

    @staticmethod
    def generate_uid():
        """
        Method to generate a unique survey id.

        :return:  ``Survey.SURVEY_UID_LEN`` letters long unique id.
        """
        survey_uid = shortuuid.ShortUUID().random(
            length=Survey.SURVEY_UID_LEN).lower()
        while Survey.objects.filter(survey_uid=survey_uid).exists():
            survey_uid = shortuuid.ShortUUID().random(
                length=Survey.SURVEY_UID_LEN).lower()

        return survey_uid
Exemplo n.º 15
0
class Form(models57.Model):
    """
    Model to define a form.

    **Authors**: Gagandeep Singh
    """
    title           = models.CharField(max_length=255, db_index=True, help_text='Title of the form which is displayed on the top.')
    description     = models.CharField(max_length=512, null=True, blank=True, help_text='(TranslationID) Description about this form.') # tinymce_models.HTMLField(null=True, blank=True, help_text='Description about this form.')
    instructions    = models.CharField(max_length=512, null=True, blank=True, help_text='(TranslationID) Any relevant instructions to fill this form.') # tinymce_models.HTMLField(null=True, blank=True, help_text='Any relevant instructions to fill this form.')
    user_notes      = tinymce_models.HTMLField(null=True, blank=True, help_text='Notes for use use only.')

    theme_skin      = models.ForeignKey(ThemeSkin, on_delete=models.PROTECT, help_text='Theme to be used for this form.')
    languages       = models.ManyToManyField(Language, blank=True, help_text='Languages that are available to the form. English is by default.')

    constants       = JSONField(default=[], null=True, blank=True, help_text='List of constants used in this form.')
    schema          = JSONField(default=[], blank=True, help_text='Form schema in json format.')
    calculated_fields = JSONField(default=[], null=True, blank=True, help_text='List of fields whoes values are calculated dynamically in the form based on a expression. These are calculated in the order of declaration.')

    # Form settings
    timeout         = models.IntegerField(default=None, null=True, blank=True, help_text='Defines the number of seconds after which form expires.')
    show_timer      = models.BooleanField(default=False, help_text='In case \'timeout\' is set, this define whether to show timer or not.')
    randomize       = models.BooleanField(default=False, help_text='Randomize field order. ONLY applicable when there are no conditions.')
    gps_enabled     = models.BooleanField(default=True, help_text="Capture user location while filling form.")
    gps_mandatory   = models.BooleanField(default=False, help_text="If true, the gps location is madatory before form starts.")
    gps_precision   = models.CharField(max_length=16, choices=GeoLocation.choices, default=GeoLocation.FINE, help_text='GPS precision choice. This will automatically set gps config.')
    gps_config      = models57.JSONField(default=None, blank=True, help_text='Gps configurations according to `gps_precision` choice resolved by :class:`form_builder.utils.GeoLocation`.')

    # Meta
    translations    = models57.ListTextField(base_field=models.CharField(max_length=128), null=False, blank=True, help_text="Comma seperated list of translations (languages.Translation) ids.")
    is_ready        = models.BooleanField(default=False, editable=False, help_text='Tells if form is ready to be executed. This is verified on the fact that schema is not empty or [].')
    version         = models.UUIDField(default=uuid.uuid4, db_index=True, help_text='Auto generated form version.')
    created_on      = CreationDateTimeField(db_index=True, help_text='Date on which this form was created.')
    updated_on      = ModificationDateTimeField(auto_now=False, null=True, blank=True, db_index=True, help_text='Date on which this form was last updated.')

    @property
    def schema_obj(self):
        sc_obj = form_schema.load_form_schema(self.schema)
        if self.randomize:
            random.shuffle(sc_obj)

        return sc_obj

    @property
    def constants_obj(self):
        if self.constants is None or self.constants == {}:
            return None
        else:
            return form_schema.load_constant_schema(self.constants)

    @property
    def calculated_fields_obj(self):
        if self.calculated_fields is None or self.calculated_fields == {}:
            return None
        else:
            return form_schema.load_calculated_fields_schema(self.calculated_fields)

    def __unicode__(self):
        return self.title

    # ---- constants ----
    def get_constants_displayable(self):
        constants_obj = self.constants_obj
        if constants_obj is None:
            return None
        else:
            list_constants = [c for c in constants_obj if c.show_on_form]
            return list_constants

    def get_constants_to_include(self):
        constants_obj = self.constants_obj
        if constants_obj is None:
            return None
        else:
            list_constants = [c for c in constants_obj if c.include_in_answers]
            return list_constants

    # ---- Fields ----


    # ---- calculated fields ----
    def get_calc_fields_displayable(self):
        calculated_fields_obj = self.calculated_fields_obj
        if calculated_fields_obj is None:
            return None
        else:
            list_calc_flds = [f for f in calculated_fields_obj if f.show_on_form]
            return list_calc_flds

    def get_calc_fields_to_include(self):
        calculated_fields_obj = self.calculated_fields_obj
        if calculated_fields_obj is None:
            return None
        else:
            list_calc_flds = [f for f in calculated_fields_obj if f.include_in_answers]
            return list_calc_flds

    # --- Form Validator ----
    def validate_form(self):
        """
        Validate form by analyzing schema, unique ids and various other necessary validations and
        return list id translation ids.
        """

        from form_builder.fields import BasicFormField

        set_translation_ids = set()

        if self.description:
            set_translation_ids.add(self.description)

        if self.instructions:
            set_translation_ids.add(self.instructions)

        list_varnames = []
        def push_list_varnames(varname):
            if list_varnames.__contains__(varname):
                raise DuplicateVariableName("Duplicate variable with label '{}'.".format(varname))
            else:
                list_varnames.append(varname)

        # (1) Parse constants JSON & obtain object form.
        constants = self.constants_obj
        if constants:
            for const in constants:
                push_list_varnames(str(const.label))
                if const.text_translation_id is not None:
                    set_translation_ids.add(const.text_translation_id)

        # (2) Parse schema JSON & obtain schema obj. This will check any schema errors.
        schema_obj = self.schema_obj
        if schema_obj is not None and len(schema_obj) != 0:
            # Check if randomization is allowed: There must be no component other than 'fields' if randomize is true
            if self.randomize:
                for comp in schema_obj:
                    if not isinstance(comp, BasicFormField):
                        raise ValidationError("You cannot use randomize since the form contains conditions & layouts.")

            # Prepare field lookup for further use
            lookupDict_fields = {}      # { "<label>": <Field Object>, "<label>":<Field Object>, ...}
            for field in iterate_form_fields(schema_obj):
                label = str(field.label)
                push_list_varnames(label)
                lookupDict_fields[label] = field
                set_translation_ids.update(field.get_translation_ids())

                self.is_ready = True
        else:
            self.is_ready = False

        # (3) Parse calculated fields & obtains object form.
        # Check that all calculated fields are using only constants or mandatory form variables.
        calc_flds = self.calculated_fields_obj
        if calc_flds:
            for calcfld in calc_flds:
                push_list_varnames(str(calcfld.label))
                list_vars_in_expr = calcfld.get_expression_variables()
                if calcfld.text_translation_id is not None:
                    set_translation_ids.add(calcfld.text_translation_id)

                for absolute_var in list_vars_in_expr:
                    varname = absolute_var.replace("$scope.", "").replace("data.", "").replace("constants.", "")
                    if not list_varnames.__contains__(varname):
                        # Check variable was declared or not
                        raise ExpressionCompileError("Undefined variable '{}' in the expression for calculated field '{}'.".format(varname, calcfld.label))
                    else:
                        # Chech if this variable is data field
                        if absolute_var.__contains__("data."):
                            # check if this field is mandatory
                            if lookupDict_fields[varname].required == False:
                                raise ExpressionCompileError("Field '{}' must be mandatory in order to be used in the expression for calculated field '{}'.".format(varname, calcfld.label))

        return list(set_translation_ids)

    # --- Translations ---
    def get_translations(self):
        return Translation.objects.filter(pk__in=self.translations)

    def get_translation_lookup(self):
        list_translations = self.get_translations()
        lookup_dict = { str(trans.pk):trans for trans in list_translations}
        return lookup_dict

    # --- Misc ---
    def humanize_timeout(self):
        secs = self.timeout
        if secs:
            mins, secs = divmod(secs, 60)
            hours, mins = divmod(mins, 60)

            s = []
            s.append(str(hours) + ' hour' + ('s' if hours > 1 else '')) if hours else None
            s.append(str(mins) + ' minute' + ('s' if mins > 1 else '')) if mins else None
            s.append(str(secs) + ' second' + ('s' if secs > 1 else '')) if secs else None
            return ", ".join(s)
        else:
            return None

    def to_json(self):
        data_dict = model_to_dict(self)
        data_dict['languages'] = list(data_dict['languages'].values_list('id', flat=True))
        data_dict['language_codes'] = list(self.languages.all().values_list('code', flat=True))
        for key, val in data_dict.iteritems():
            if isinstance(val, uuid.UUID):
                data_dict[key] = str(val)
            elif isinstance(val, datetime):
                data_dict[key] = val.isoformat()
        return data_dict

    def get_formquestions(self, only_current=True):
        """
        Method to return form questions for this form.

        :param only_current: If True, returns only those questions which are currently in the form.
            Otherwise returns all questions including those which have been changed.
        :return: List<:class:`form_builder.models.FormQuestion`>

        **Authors**: Gagandeep Singh
        """

        if only_current:
            qry = self.formquestion_set.filter(form_version=self.version)
        else:
            qry = self.formquestion_set.all()
        return qry


    # --- Clean & Save ---
    def clean(self):
        list_translation_ids = self.validate_form()
        # print list_translation_ids
        self.translations = list_translation_ids

        # Gps Settings
        self.gps_config = GeoLocation.config[self.gps_precision]
        if self.gps_enabled == False and self.gps_mandatory == True:
            raise ValidationError("GPS must be enabled before it is marked as mandatory.")

        if self.id:
            self.updated_on = timezone.now()

        super(Form, self).clean()

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

        if self.id:
            self.version = uuid.uuid4()

        #self.validate_form()
        return super(Form, self).save(*args, **kwargs)

    @classmethod
    def post_save(cls, sender, instance, **kwargs):
        schema_obj = instance.schema_obj
        if schema_obj is not None and len(schema_obj) != 0:
            for fld in iterate_form_fields(schema_obj):
                # print "\tPushing :" , fld.label
                FormQuestion.objects.update_or_create(
                    form_id = instance.id,
                    label = fld.label,
                    field_class = fld._cls,
                    defaults = {
                        "form_version": instance.version,
                        "text_translation_id": fld.text_translation_id,
                        "schema_json": fld.to_json(),
                        "dated": timezone.now()
                    }
                )
Exemplo n.º 16
0
class Organization(models57.Model):
    """
    An organization is an legal registered entity such as Company, Firm, Agency, Government or non-government organization, NGO etc.

    **State chart diagram for organization status**:

        .. image:: ../../_static/clients/organization_status_statechart.jpg

    **Points**:

        - **Status**:
            - ``frozen``: Means all operations of this organization have been ceased. No one can add update or create
              anything. Only viewing is allowed. This can be unfreeze to ``verified`` state.
            - ``deleted``: Means this organization has been permanently deleted from the system. It cannot be revived now.
        - Please call save after all transition method calls.
        - If verification fails, it is mandatory to provide reason. This reason will be shown to the user.
        - **Claims** on the organization can disabled if organization is known such as top organization or contracted clients. This can
          **ONLY** be done by staff user. Owner do not have rights to set this property.
        - To make changes in fields take care the following:
            - For Logo & icon dimensions & size constraints (must not change), make changes in
              LOGO_DIM, LOGO_MAX_SIZE etc in organization enums.
            - Make changes in :class:``market.forms.OrganizationCreateEditForm``.
            - Make changes for client side validations in '/static/partials/market/create_edit_organization.html'.
            - Make changes in 'market/templates/market/console/organization_settings.html'. Also in review modal.
            - Make updates in 'market.operations.*'.

    **Authors**: Gagandeep Singh
    """
    # --- Enums ---
    LOGO_DIM = (300, 100)
    LOGO_MAX_SIZE = 30*1024 # in bytes

    ICON_DIM = (64, 64)
    ICON_MAX_SIZE = 15*1024 # in bytes

    TYPE_PUBLIC = 'public'
    TYPE_PRIVATE = 'private'
    TYPE_GOV = 'government'
    TYPE_NGO = 'ngo'
    CH_TYPE = (
        (TYPE_PUBLIC, 'Public'),
        (TYPE_PRIVATE, 'Private'),
        (TYPE_GOV, 'Government'),
        (TYPE_NGO, 'NGO'),
    )

    ST_VERF_PENDING = 'verification_pending'
    ST_VERIFIED = 'verified'
    ST_VERF_FAILED = 'verification_failed'
    ST_FROZEN = 'frozen'
    ST_DELETED = 'deleted'
    CH_STATUS = (
        (ST_VERF_PENDING, 'Verification pending'),
        (ST_VERIFIED, 'Verified'),
        (ST_VERF_FAILED, 'Verification failed'),
        (ST_FROZEN, 'Frozen'),
        (ST_DELETED, 'Deleted')
    )

    # --- Fields ---
    org_uid     = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False, help_text='Unique ID of an organization. This is mostly used in url in management console.')
    name        = models.CharField(max_length=255, unique=True, db_index=True, help_text='Name of the organization.')
    slug        = models.SlugField(unique=True, blank=True, db_index=True, editable=False, help_text='Slug of the name. Used in urls for public view.')
    acronym     = models.CharField(max_length=10, null=True, blank=True, help_text='Acronym of the organization if any.')

    # Settings
    # description = tinymce_models.HTMLField(help_text='Short description about the organization.')
    description = models.TextField(help_text='Short description about the organization.')
    type        = models.CharField(max_length=32, choices=CH_TYPE, help_text='Type of the organization.')
    logo        = models.ImageField(max_length=256, upload_to=upload_organization_logo_to, help_text='Organization logo of size 300x100 pixels.')
    icon        = models.ImageField(max_length=256, upload_to=upload_organization_icon_to, help_text='Organization icon of size 64x64 px.')

    # Customization
    # banner
    # splashscreen
    ui_theme    = models57.JSONField(default=None, blank=True, null=True, help_text="Custom UI theme for this organization. This must be of format 'utilities.theme.UiTheme'")
    theme_file  = models.FileField(max_length=256, upload_to=upload_organization_theme_file_to, editable=False, help_text='Theme file link which is automatically generated if ui_theme is defined')

    members     = models.ManyToManyField(RegisteredUser, through='OrganizationMember', help_text='Members of this organization.')

    # Statuses
    status      = FSMField(default=ST_VERF_PENDING, choices=CH_STATUS, protected=True, db_index=True, editable=False, help_text='Verification status of the organization.')
    failed_reason = tinymce_models.HTMLField(null=True, blank=True, help_text='Reason stating why this organization was failed during verification. This is shown to the user.')
    disable_claim = models.BooleanField(default=False, help_text='Set true to stop any further claims on this organization. Only staff can set this property, user cannot.')

    # Other
    staff_remarks = tinymce_models.HTMLField(null=True, blank=True, help_text='Remarks filled by staff. This can be related to anything such as user interaction for verification.')

    # Misc
    created_by  = models.ForeignKey(User, editable=False, help_text='User that created this organization. This can be a staff or registered user.')
    created_on  = models.DateTimeField(auto_now_add=True, editable=False, db_index=True, help_text='Date on which this record was created.')
    modified_on = models.DateTimeField(null=True, blank=True, editable=False, help_text='Date on which this record was modified.')

    class Meta:
        ordering = ('name', )

    def __unicode__(self):
        return "{}: {}".format(self.id, self.name)

    # --- Transitions ---
    @fsm_log_by
    @transition(field=status, source=ST_VERF_PENDING, target=ST_VERIFIED)
    def trans_verification_success(self, remarks=None):
        """
        Transition edge to transit organization status to verified.

        **Authors**: Gagandeep Singh
        """
        self.staff_remarks = remarks

    @fsm_log_by
    @transition(field=status, source=ST_VERF_PENDING, target=ST_VERF_FAILED)
    def trans_verification_failure(self, reason):
        """
        Transition edge for organization verification failed. A reason must be provided stating
        why verification was failed.

        **Authors**: Gagandeep Singh
        """
        self.failed_reason = reason

    @fsm_log_by
    @transition(field=status, source=ST_VERF_FAILED, target=ST_VERF_PENDING)
    def trans_revise_verification(self):
        """
        Transition edge to revise organization verification. This means organization has been edited and
        now again queued for verification.

        **Authors**: Gagandeep Singh
        """
        pass

    @fsm_log_by
    @transition(field=status, source=ST_VERIFIED, target=ST_FROZEN)
    def trans_freeze(self):
        """
        Transition edge to freeze organization. This is done to cease all organization's operations.

        **Authors**: Gagandeep Singh
        """
        pass

    @fsm_log_by
    @transition(field=status, source=ST_FROZEN, target=ST_VERIFIED)
    def trans_unfreeze(self):
        """
        Transition edge to unfreeze organization. This is done to restore all organization's operations.

        **Authors**: Gagandeep Singh
        """
        pass

    @fsm_log_by
    @transition(field=status, source=[ST_VERF_PENDING, ST_VERIFIED, ST_VERF_FAILED, ST_FROZEN], target=ST_DELETED)
    def trans_delete(self):
        """
        Transition edge to mark this organization as deleted. Use this method with caution.
        Once marked, all operations on the organization are stopped and everything is freezed.
        You cannot edit this organization and its entities however, you can view them.

        **Authors**: Gagandeep Singh
        """
        pass
    # --- /Transitions ---

    def update_theme_files(self, auto_save=True):
        """
        Method to update all theme files only if ui_theme is defined.

        :return: (bool) True if file was created and set to the field (irrespective of save), False if ui_theme was not set.

        **Authors**: Gagandeep Singh
        """
        if self.ui_theme:
            ui_theme = UiTheme(self.ui_theme)

            # render file
            content = render_skin(
                custom=True,
                clr_primary = ui_theme.primary,
                clr_prim_hover = ui_theme.primary_dark,
                clr_prim_disabled = ui_theme.primary_disabled
            )

            # Create InMemoryUploadObject
            f_io = StringIO.StringIO(content)
            mem_file_css = InMemoryUploadedFile(
                f_io,
                u'file',
                'theme.css',
                u'text/css',
                f_io.len,
                None
            )

            self.theme_file = mem_file_css

            if auto_save:
                self.save()

            return True
        else:
            return False

    def get_edit_json(self):
        """
        Method to return json for edit form.

        :return: JSON

        **Authors**: Gagandeep Singh
        """
        return {
            "id": self.id,
            "name": self.name,
            "acronym": self.acronym if self.acronym else None,
            "description": self.description,
            "type": self.type,

            "ui_theme__primary": self.ui_theme.get('primary') if self.ui_theme else None
        }

    def clean(self):
        """
        Method to clean & validate data fields.

        **Authors**: Gagandeep Singh
        """

        if self.pk:
            # Update modified date
            self.modified_on = timezone.now()

        # Name slug
        if not self.slug:
            self.slug = slugify(self.name)

        if self.acronym == '':
            self.acronym = None

        # Images
        if not Organization.validate_logo_image(self.logo):
            raise ValidationError('Logo must be {}x{} and less than {} KB.'.format(
                Organization.LOGO_DIM[0],
                Organization.LOGO_DIM[1],
                Organization.LOGO_MAX_SIZE/1024
            ))
        if not Organization.validate_icon_image(self.icon):
            raise ValidationError('Icon must be {}x{} and less than {} KB.'.format(
                Organization.ICON_DIM[0],
                Organization.ICON_DIM[1],
                Organization.ICON_MAX_SIZE/1024
            ))

        # Check UI Theme
        if self.ui_theme is not None:
            if self.ui_theme == {}:
                self.ui_theme = None
            else:
                try:
                    theme_obj = UiTheme(self.ui_theme)
                except Exception as ex:
                    raise ValidationError("ui_theme: " + ex.message)

        # Status related validations
        if self.status == Organization.ST_VERF_FAILED and self.failed_reason in [None, '']:
            raise ValidationError("Please provide reason for verification failure.")

        super(self.__class__, self).clean()

    def save(self, update_theme=False, *args, **kwargs):
        """
        Pre-save method for this model.

        **Authors**: Gagandeep Singh
        """
        self.clean()

        # Update theme
        if update_theme:
            # Theme errors have been checked in clean()
            self.update_theme_files(auto_save=False)

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

    def delete(self, using=None, keep_parents=False):
        """
        Pre-delete method. (Not allowed)

        **Authors**: Gagandeep Singh
        """
        raise ValidationError("You cannot delete an organization. Please use 'trans_delete()' method to mark this as deleted.")

    # ----- Static methods -----
    @staticmethod
    def generate_uitheme(primary_color):
        """
        Method to generate ui theme json wrapper :class:`utilities.theme.UiTheme`.

        :param primary_color: Primary color in hex format
        :return: :class:`utilities.theme.UiTheme` instance

        **Authors**: Gagandeep Singh
        """
        # from utilities.theme import UiTheme, ColorUtils
        return UiTheme(
            primary = primary_color,
            primary_dark = ColorUtils.scale_hex_color(primary_color, -40),
            primary_disabled = ColorUtils.scale_hex_color(primary_color, 60)
        )

    @staticmethod
    def does_exists(name):
        """
        Method to check if organization exists with given name or with slug of given name.

        :param name: Name of the organization
        :return: (bool) True if organization exists else False

        **Authors**: Gagandeep Singh
        """
        slug = slugify(name)
        return Organization.objects.filter(Q(name=name)|Q(slug=slug))

    @staticmethod
    def validate_logo_image(img_obj):
        """
        Method to validate organization logo image.
        Handles both ``InMemoryUploadedFile`` and ``ImageFieldFile`` objects.

        :param img_obj: InMemory object of image
        :return: True if image is valid

        **Authors**: Gagandeep Singh
        """
        if isinstance(img_obj, InMemoryUploadedFile):
            # InMemory object
            size = img_obj.size
            dim = Image.open(img_obj).size
        elif isinstance(img_obj, ImageFieldFile):
            # Django model field from ImageField
            size = img_obj._get_size()
            dim = img_obj._get_image_dimensions()

        return (size <= Organization.LOGO_MAX_SIZE and dim == Organization.LOGO_DIM)

    @staticmethod
    def validate_icon_image(img_obj):
        """
        Method to validate organization icon image.
        Handles both ``InMemoryUploadedFile`` and ``ImageFieldFile`` objects.

        :param img_obj: InMemory object of image
        :return: True if image is valid

        **Authors**: Gagandeep Singh
        """
        if isinstance(img_obj, InMemoryUploadedFile):
            # InMemory object
            size = img_obj.size
            dim = Image.open(img_obj).size
        elif isinstance(img_obj, ImageFieldFile):
            # Django model field from ImageField
            size = img_obj._get_size()
            dim = img_obj._get_image_dimensions()

        return (size <= Organization.ICON_MAX_SIZE and dim == Organization.ICON_DIM)
Exemplo n.º 17
0
class OrdersInfo(model0.Model):
    """订单表模型类"""

    trans_code = model0.CharField(max_length=32,
                                  null=True,
                                  blank=True,
                                  unique=True,
                                  verbose_name='转单号')
    order_status = model0.SmallIntegerField(
        choices=settings.ORDER_STATUS_CHOICE, default=1, verbose_name='订单状态')
    freight = model0.ForeignKey(to='FreightsInfo',
                                related_name='orders',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属运单')
    customer = model0.ForeignKey(to='customers.CustomersInfo',
                                 related_name='orders',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属客户')
    channel = model0.ForeignKey(to='systems.DataDictsValue',
                                related_name='orders_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属渠道')
    good_type = model0.ForeignKey(to='systems.DataDictsValue',
                                  related_name='orders_g',
                                  on_delete=model0.SET_NULL,
                                  null=True,
                                  blank=True,
                                  db_constraint=False,
                                  db_index=False,
                                  verbose_name='所属货物类型')
    pay_type = model0.ForeignKey(to='systems.DataDictsValue',
                                 related_name='orders_p',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属付款类型')
    operators = model0.ManyToManyField(to='systems.UsersInfo',
                                       related_name='users',
                                       through='Order2Operator',
                                       through_fields=('order', 'operator'),
                                       blank=True,
                                       db_index=False,
                                       verbose_name='操作员')
    collection_money = model0.FloatField(max_length=12,
                                         default=0,
                                         null=True,
                                         verbose_name='代收金额')
    v_w_rate = model0.FloatField(max_length=12,
                                 null=True,
                                 verbose_name='体积重量比')
    volume = model0.FloatField(max_length=12, null=True, verbose_name='体积')
    volume_w = model0.FloatField(max_length=12, null=True, verbose_name='体积重')
    weight = model0.FloatField(max_length=12, null=True, verbose_name='重量')
    price_w = model0.FloatField(max_length=12, null=True, verbose_name='价格重量')
    number = model0.IntegerField(null=True, verbose_name='包裹件数')
    transport_site = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='起运地点')
    goods_name = model0.TextField(max_length=300,
                                  null=True,
                                  blank=True,
                                  verbose_name='货物名称')
    goods_name_en = model0.TextField(max_length=300,
                                     null=True,
                                     blank=True,
                                     verbose_name='货物名称(英文)')
    flight_number = model0.CharField(max_length=64,
                                     null=True,
                                     blank=True,
                                     verbose_name='航班号')
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='备注')
    order_time = model0.DateTimeField(null=True, verbose_name="订单时间")
    receiver = model0.ForeignKey(to='customers.ReceiversInfo',
                                 related_name='orders_r',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='收货方')

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='orders_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='orders_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'business'
        db_table = 'b_orders'
        verbose_name = '订单'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.trans_code
Exemplo n.º 18
0
class FreFundsInfo(model0.Model):
    """货运款项 模型类"""

    freight = model0.ForeignKey(to='business.FreightsInfo',
                                related_name='freight_funds',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属运单')
    fund_status = model0.SmallIntegerField(choices=settings.FUND_STATUS_CHOICE,
                                           default=1,
                                           verbose_name='款项状态')
    freight_status = model0.SmallIntegerField(
        choices=settings.FREIGHT_STATUS_CHOICE, default=1, verbose_name='运单状态')
    pay_type = model0.ForeignKey(to='systems.DataDictsValue',
                                 related_name='freight_funds_p',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属付款类型')
    trans_company = model0.ForeignKey(to='systems.DataDictsValue',
                                      related_name='freight_funds_t',
                                      on_delete=model0.SET_NULL,
                                      null=True,
                                      blank=True,
                                      db_constraint=False,
                                      db_index=False,
                                      verbose_name='货运公司')
    mid_company = model0.ForeignKey(to='systems.DataDictsValue',
                                    related_name='freights_funds_m',
                                    on_delete=model0.SET_NULL,
                                    null=True,
                                    blank=True,
                                    db_constraint=False,
                                    db_index=False,
                                    verbose_name='中港公司')
    channel = model0.ForeignKey(to='systems.DataDictsValue',
                                related_name='freight_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属渠道')
    service = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='freight_funds_s',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='款项专员')
    price_w = model0.FloatField(max_length=12, null=True, verbose_name='价格重量')
    y_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='应付金额')
    s_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='实付金额',
                                  default=0)
    j_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='减免金额',
                                  default=0)
    w_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='未结算金额')
    freight_fee = model0.FloatField(max_length=12,
                                    null=True,
                                    verbose_name='运费')
    lading_fee = model0.FloatField(max_length=12,
                                   null=True,
                                   verbose_name='提单费',
                                   default=0)
    magntest_fee = model0.FloatField(max_length=12,
                                     null=True,
                                     verbose_name='磁检费',
                                     default=0)
    operate_fee = model0.FloatField(max_length=12,
                                    null=True,
                                    verbose_name='操作费',
                                    default=0)
    file_fee = model0.FloatField(max_length=12,
                                 null=True,
                                 verbose_name='文件费',
                                 default=0)
    custclea_fee = model0.FloatField(max_length=12,
                                     null=True,
                                     verbose_name='报关费',
                                     default=0)
    collection_money = model0.FloatField(max_length=12,
                                         null=True,
                                         verbose_name='代付金额')
    other_fee = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='其他费用',
                                  default=0)
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='减免说明')
    attachment_ids = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='附件列表')
    pack_time = model0.DateTimeField(null=True, verbose_name="打包时间")

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='freight_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='freight_funds_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'funds'
        db_table = 'b_fre_funds'
        verbose_name = '货运款项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.freight.freight_code
Exemplo n.º 19
0
class OtherFundsInfo(model0.Model):
    """其他款项"""
    fund_code = model0.CharField(max_length=32,
                                 null=True,
                                 blank=True,
                                 verbose_name='款号')
    fund_type = model0.SmallIntegerField(
        choices=settings.OTHER_FUND_TYPE_CHOICE,
        null=True,
        verbose_name='款项类型')
    fund_status = model0.SmallIntegerField(choices=settings.FUND_STATUS_CHOICE,
                                           default=1,
                                           verbose_name='款项状态')
    order = model0.ForeignKey(to='business.OrdersInfo',
                              related_name='other_funds_o',
                              on_delete=model0.SET_NULL,
                              null=True,
                              blank=True,
                              db_constraint=False,
                              db_index=False,
                              verbose_name='所属订单')
    freight = model0.ForeignKey(to='business.FreightsInfo',
                                related_name='other_funds_f',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属运单')
    service = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='other_funds_s',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='款项专员')
    payee_payer = model0.CharField(max_length=64,
                                   null=True,
                                   blank=True,
                                   verbose_name='收/付款方名称')
    connect_ways = model0.CharField(max_length=32,
                                    null=True,
                                    blank=True,
                                    verbose_name='收/付款方联系方式')
    y_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='应收/付金额')
    s_account = model0.FloatField(max_length=12,
                                  null=True,
                                  verbose_name='实收/付金额')
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='款项说明')
    attachment_ids = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='附件列表')
    recpay_time = model0.DateField(null=True, verbose_name="收/付款时间")

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='other_funds_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='other_funds_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'funds'
        db_table = 'b_oth_funds'
        verbose_name = '其他款项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.fund_code
Exemplo n.º 20
0
class FreightsInfo(model0.Model):
    """运单 模型类"""

    freight_code = model0.CharField(max_length=32,
                                    null=True,
                                    blank=True,
                                    verbose_name='运单号')
    freight_status = model0.SmallIntegerField(
        choices=settings.FREIGHT_STATUS_CHOICE, default=1, verbose_name='运单状态')
    channel = model0.ForeignKey(to='systems.DataDictsValue',
                                related_name='freights_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='所属渠道')
    pay_type = model0.ForeignKey(to='systems.DataDictsValue',
                                 related_name='freights_p',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='所属付款类型')
    trans_company = model0.ForeignKey(to='systems.DataDictsValue',
                                      related_name='freights_t',
                                      on_delete=model0.SET_NULL,
                                      null=True,
                                      blank=True,
                                      db_constraint=False,
                                      db_index=False,
                                      verbose_name='货运公司')
    mid_company = model0.ForeignKey(to='systems.DataDictsValue',
                                    related_name='freights_m',
                                    on_delete=model0.SET_NULL,
                                    null=True,
                                    blank=True,
                                    db_constraint=False,
                                    db_index=False,
                                    verbose_name='中港公司')
    kits = model0.IntegerField(null=True, verbose_name='货物件数')
    weight = model0.FloatField(max_length=12, null=True, verbose_name='总重量')
    volume = model0.FloatField(max_length=12, null=True, verbose_name='总体积')
    price_w = model0.FloatField(max_length=12, null=True, verbose_name='价格重')
    volume_w = model0.FloatField(max_length=12, null=True, verbose_name='体积重')
    collection_money = model0.FloatField(max_length=12,
                                         null=True,
                                         verbose_name='代收金额')
    transport_site = model1.JSONField(null=True,
                                      blank=True,
                                      verbose_name='起运地点')
    order_codes = model1.JSONField(max_length=1000,
                                   null=True,
                                   blank=True,
                                   verbose_name='订单号')
    mid_port = model0.CharField(max_length=100,
                                null=True,
                                blank=True,
                                verbose_name='中转站')
    flight_number = model0.CharField(max_length=64,
                                     null=True,
                                     blank=True,
                                     verbose_name='航班号')
    remark_comment = model0.TextField(max_length=300,
                                      null=True,
                                      blank=True,
                                      verbose_name='备注')
    pack_time = model0.DateTimeField(auto_now_add=True,
                                     null=True,
                                     verbose_name="打包时间")

    creator = model0.ForeignKey(to='systems.UsersInfo',
                                related_name='freights_c',
                                on_delete=model0.SET_NULL,
                                null=True,
                                blank=True,
                                db_constraint=False,
                                db_index=False,
                                verbose_name='创建人')
    modifier = model0.ForeignKey(to='systems.UsersInfo',
                                 related_name='freights_u',
                                 on_delete=model0.SET_NULL,
                                 null=True,
                                 blank=True,
                                 db_constraint=False,
                                 db_index=False,
                                 verbose_name='修改人')
    create_time = model0.DateTimeField(auto_now_add=True,
                                       null=True,
                                       verbose_name="创建时间")
    modify_time = model0.DateTimeField(auto_now=True,
                                       null=True,
                                       verbose_name="修改时间")

    class Meta:
        app_label = 'business'
        db_table = 'b_freights'
        verbose_name = '运单'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.freight_code