Exemplo n.º 1
0
class DumbDocument(Document):
    name = fields.StringField()
    foo = fields.IntField()
Exemplo n.º 2
0
class CustomIdModel(Document):
    id = fields.StringField(primary_key=True)
Exemplo n.º 3
0
class Measures(Document):
    name = fields.StringField(required=True, max_length=30)
    indications = fields.StringField(required=True, max_length=500)
Exemplo n.º 4
0
class Quotation(InvoiceBase, InvoiceMakableMixin, SearchDocumentMixin):
    """Quotations specific class."""
    TYPE = "QUOTATION"
    RECORD_NAME = _("Quotation")
    STATES = QUOTATION_STATES
    QUOTATION_VALIDITY_PERIODS = (15, 30, 45, 60, 90)

    state = fields.StringField(required=True,
                               choices=STATES,
                               default=STATES.DRAFT)
    current_revision = fields.EmbeddedDocumentField("QuotationRevision",
                                                    required=True)
    revisions = fields.ListField(
        fields.EmbeddedDocumentField("QuotationRevision"))

    meta = {"allow_inheritance": True}

    class Meta():
        document_type = 'quotation'
        document_boost = 0.9
        fields = [
            search_mappings.StringField(name="reference",
                                        boost=document_boost * 3.0,
                                        index="analyzed",
                                        term_vector="with_positions_offsets"),
            search_mappings.StringField(name="related_invoice_reference",
                                        boost=document_boost * 1.5,
                                        index="analyzed",
                                        term_vector="with_positions_offsets"),
            search_mappings.StringField(name="contact",
                                        index="analyzed",
                                        term_vector="with_positions_offsets"),
            search_mappings.StringField(name="organization",
                                        index="analyzed",
                                        term_vector="with_positions_offsets"),
            search_mappings.DateField(name="quotation_date",
                                      index="analyzed",
                                      term_vector="with_positions_offsets",
                                      include_in_all=False),
            search_mappings.StringField(name="state",
                                        index="not_analyzed",
                                        term_vector="with_positions_offsets",
                                        include_in_all=False),
        ]

    class InvalidState(InvalidInvoiceBaseState):
        def __init__(self, **kwargs):
            super(Quotation.InvalidState, self).__init__(**kwargs)
            self.message = 'Invalid quotation state'

    def get_search_kwargs(self):
        kwargs = super(Quotation, self).get_search_kwargs()
        if self.current_revision.quotation_date:
            kwargs.update(quotation_date=self.current_revision.quotation_date)
        if self.group.invoice:
            kwargs.update(
                related_invoice_reference=self.group.invoice.reference)
        return kwargs

    @classmethod
    def pre_save(self, sender, document, **kwargs):
        """
        Pre save hook handler

        - Set the type and reference
        """
        # Calling parent
        super(Quotation, document).pre_save(sender, document, **kwargs)

        if not document.is_created():
            document.base_type = document.TYPE
            document.reference = document.genere_reference(
                document.tenant.tenant_settings)

    @classmethod
    def post_save(self, sender, document, created, **kwargs):
        """
        Post save hook handler

        If created:

        - increments the appropriate :class:`~core.models.Tenant` quotations numbering counter.
        - set the quotation to the group
        """
        if created:
            document.tenant.tenant_settings.increment_quotation_counter()
            document.group.quotation = document
            document.group.save()

        # Calling parent
        super(Quotation, document).post_save(sender, document, created,
                                             **kwargs)

    def genere_reference(self, tenant_settings):
        """
        Genere a unique reference for an :class:`~invoicing.models.Quotation` object.

        Use the :class:`~core.models.Tenant` quotations numbering counter.
        """
        if tenant_settings.invoicing.numbering.scheme == "DN":
            date = unicode(
                datetime.datetime.strftime(
                    datetime.datetime.now(),
                    tenant_settings.invoicing.numbering.DATE_STRFTIME_FORMATS[
                        tenant_settings.invoicing.numbering.date_format]))
            counter = unicode("%0*d" %
                              (5, tenant_settings.get_quotation_counter()))
            elements = (date, counter)
        elif tenant_settings.invoicing.numbering.scheme == "N":
            counter = unicode("%0*d" %
                              (5, tenant_settings.get_quotation_counter()))
            elements = (counter, )
        else:
            return False
        return unicode(
            tenant_settings.invoicing.numbering.separator).join(elements)

    def is_quotation(self):
        return True

    def is_modifiable(self):
        """A :class:`~invoicing.models.Quotation` is modifiable unless it has been invoiced."""
        if self.group.invoice:
            return False
        return True

    def is_deletable(self):
        """
        A :class:`~invoicing.models.Quotation` is deletable if not linked to any
        :class:`~invoicing.models.Invoice` or :class:`~invoicing.models.DownPaymentInvoice`.
        """
        if self.group.invoice or self.group.down_payment_invoices:
            return False
        return True

    def is_issuable(self):
        """Determine if the :class:`~invoicing.models.Quotation` could be sent."""
        if self.state not in (Quotation.STATES.DRAFT, ):
            return True
        return False

    def get_possible_states(self):
        """
        List the available states for the :class:`~invoicing.models.Quotation`,
        depending of its current state.
        """
        if self.state == Quotation.STATES.DRAFT:
            return [
                Quotation.STATES.AWAITING_APPROVAL, Quotation.STATES.APPROVED,
                Quotation.STATES.REFUSED
            ]
        elif self.state == Quotation.STATES.AWAITING_APPROVAL:
            return [Quotation.STATES.APPROVED, Quotation.STATES.REFUSED]
        elif self.state == Quotation.STATES.EXPIRED:
            return [
                Quotation.STATES.AWAITING_APPROVAL, Quotation.STATES.APPROVED,
                Quotation.STATES.REFUSED
            ]
        elif self.state == Quotation.STATES.REFUSED:
            return [
                Quotation.STATES.AWAITING_APPROVAL, Quotation.STATES.APPROVED
            ]
        else:
            return []

    def make_purchase_order(self, issuer):
        """Creates a purchase order based on the current quotation"""
        from invoicing.models import PurchaseOrder, PurchaseOrderRevision

        # Initialize the purchase order
        purchase_order = PurchaseOrder(full_init=False,
                                       tenant=self.tenant,
                                       account_type=self.account_type,
                                       issuer=issuer,
                                       organization=self.organization,
                                       contact=self.contact,
                                       group=self.group,
                                       attachments=self.attachments)

        # Save the purchase order, based on the quotation
        purchase_order_data = purchase_order.add_revision(
            revision=PurchaseOrderRevision(based_on=self.current_revision))
        purchase_order_data.state = purchase_order.state
        purchase_order_data.issuer = issuer
        purchase_order_data.issue_date = datetime_now()
        purchase_order_data.purchase_order_date = datetime.date.today()
        purchase_order.save()
        return purchase_order

    @classmethod
    def post_make_purchase_order(cls, sender, issuer, document, new_document,
                                 **kwargs):
        """
        Post make purchase order hook handler

        - Add timeline and notification entries
        """
        # Add timeline and notification entries
        post_make_purchase_order_task.delay(issuer, document, new_document)

    @staticmethod
    def manage_states():
        """
        An :class:`~invoicing.models.Quotation` state can be modified by the time.

        This method allows tasks scripts to update Quotations state on a regular basis.
        """
        today = datetime.date.today()
        Quotation.objects\
            .filter(state=Quotation.STATES.AWAITING_APPROVAL, current_revision__quotation_validity__lt=today)\
            .update(set__state=Quotation.STATES.EXPIRED)

    @staticmethod
    def full_export(tenant, start_date=None, end_date=None):
        def get_path(quotation):
            quotation_date = quotation.current_revision.quotation_date or quotation.current_revision.issue_date
            return '{0}/{1}/{2}'.format(ugettext('Quotations'),
                                        quotation_date.strftime('%Y/%m'),
                                        quotation.filename)

        def get_doc(quotation):
            return quotation.gen_pdf().getvalue()

        kwargs = {'tenant': tenant}
        if start_date:
            kwargs.update(current_revision__quotation_date__gte=start_date)
        if end_date:
            kwargs.update(current_revision__quotation_date__lt=end_date)
        queryset = Quotation.objects.filter(**kwargs)
        return queryset, get_path, get_doc

    def remove_invoiced_state(self):
        if self.current_revision.quotation_validity and self.current_revision.quotation_validity < datetime.date.today(
        ):
            self.state = QUOTATION_STATES.EXPIRED
        else:
            self.state = QUOTATION_STATES.APPROVED
Exemplo n.º 5
0
class Major(Document):
    major_name = fields.StringField(required=True)
Exemplo n.º 6
0
class OneFieldModel(Document):
    str_field = fields.StringField()
Exemplo n.º 7
0
class User(BaseDocument, UserMixin):

    email = fields.StringField(required=False, unique=True, max_length=200)
    #username = fields.StringField(required=False, unique=True, max_length=200)

    password = fields.StringField(max_length=200)

    #TODO: last_ip, last_login

    api_key = fields.StringField(max_length=255)

    locale = fields.StringField()

    confirmed_at = fields.DateTimeField()

    remember_token = fields.StringField(max_length=255)

    authentication_token = fields.StringField(max_length=255)

    first_name = fields.StringField(max_length=120)

    last_name = fields.StringField(max_length=120)

    roles = fields.ListField(fields.ReferenceField(Role,
                                                   reverse_delete_rule=DENY),
                             default=[])

    @property
    def username(self):
        return self.email

    @property
    def is_active(self):
        return self.active

    @property
    def cn(self):
        if not self.first_name or not self.last_name:
            return self.email
        return u"{} {}".format(self.first_name, self.last_name)

    @property
    def id(self):
        return self.pk

    @classmethod
    def by_email(cls, email):
        return cls.objects(email=email).first()

    @property
    def gravatar(self):
        email = self.email.strip()
        encoded = hashlib.md5(email.encode("utf-8")).hexdigest()
        return "https://secure.gravatar.com/avatar/%s.png" % encoded

    def social_connections(self):
        return SocialConnection.objects(user=self)

    def __unicode__(self):
        return self.email

    meta = {
        'collection': 'user',
        'indexes': ['email',
                    'api_key'],  #TODO: dans les 2 sens pour query optimisé
    }
Exemplo n.º 8
0
class Workflow(EmbeddedDocument):
    name = fields.StringField(max_length=400, primary_key=True)
Exemplo n.º 9
0
class Prep(EmbeddedDocument):
    name = fields.StringField(max_length=400, primary_key=True)
    campaign = fields.StringField(max_length=400)
    priority = fields.IntField(default=0)
    cpus = fields.IntField(default=0)
    memory = fields.IntField(default=0)
Exemplo n.º 10
0
class ArticleModel(Document):
    _id = fields.StringField()
    body = fields.StringField()
    title = fields.StringField()
    tags = fields.ListField()
Exemplo n.º 11
0
class TaskSiteStatus(EmbeddedDocument):
    site = fields.StringField(max_length=400)
    dataset = fields.StringField(max_length=2000)
    success_count = fields.IntField(default=0)
    failed_count = fields.IntField(default=0)
Exemplo n.º 12
0
class IObject(mongoengine.Document):
    name = fields.StringField()
    pinputs = fields.ListField(fields.EmbeddedDocumentField(Parameter))
Exemplo n.º 13
0
class Parameter(mongoengine.EmbeddedDocument):
    name = fields.StringField()
Exemplo n.º 14
0
class Session(DBModel):
    chat_id = fields.StringField(unique=True, required=True)
    created_by = fields.StringField(required=True)
    service = fields.FloatField(default=0)
    tax = fields.FloatField(default=0)
    meta = {"collection": "sessions"}
Exemplo n.º 15
0
class Carrier(Document):
    name = fields.StringField(max_length=100)
    address = fields.StringField()
    phone = fields.StringField(max_length=15)

    meta = {'collection': 'carriers'}
Exemplo n.º 16
0
class WorkflowToUpdate(Document):
    name = fields.StringField(max_length=400, primary_key=True)
    updated = fields.DateTimeField()
Exemplo n.º 17
0
class VehiclePin(Document):
    user = fields.StringField()
    vehicle = fields.StringField()

    meta = {'collection': 'vehiclepins'}
Exemplo n.º 18
0
class Site(Document):
    name = fields.StringField(max_length=400, primary_key=True)
Exemplo n.º 19
0
class SocialConnection(BaseDocument):

    user = fields.ReferenceField(User)

    provider = fields.StringField(max_length=255)

    profile_id = fields.StringField(max_length=255)

    username = fields.StringField(max_length=255)

    email = fields.StringField(max_length=255)

    access_token = fields.StringField(max_length=255)

    secret = fields.StringField(max_length=255)

    first_name = fields.StringField(max_length=255,
                                    help_text=gettext("First Name"))

    last_name = fields.StringField(max_length=255,
                                   help_text=gettext("Last Name"))

    cn = fields.StringField(max_length=255, help_text=gettext("Common Name"))

    profile_url = fields.StringField(max_length=512)

    image_url = fields.StringField(max_length=512)

    def get_user(self):
        return self.user

    @classmethod
    def by_profile(cls, profile):
        provider = profile.data["provider"]
        return cls.objects(provider=provider, profile_id=profile.id).first()

    @classmethod
    def from_profile(cls, user, profile):
        if not user or user.is_anonymous:
            email = profile.data.get("email")
            if not email:
                msg = "Cannot create new user, authentication provider did not not provide email"
                logging.warning(msg)
                raise Exception(_(msg))
            conflict = User.objects(email=email).first()
            if conflict:
                msg = "Cannot create new user, email {} is already used. Login and then connect external profile."
                msg = _(msg).format(email)
                logging.warning(msg)
                raise Exception(msg)

            now = utils.utcnow()
            user = User(
                email=email,
                first_name=profile.data.get("first_name"),
                last_name=profile.data.get("last_name"),
                confirmed_at=now,
                active=True,
            )
            user.save()

        connection = cls(user=user, **profile.data)
        connection.save()
        return connection

    def __unicode__(self):
        return self.email

    meta = {
        'collection': 'socialconnection',
        'indexes': ['user', 'profile_id'],
    }
Exemplo n.º 20
0
class employees(Document):
    empId = fields.IntField(required=True, null=False)
    empName = fields.StringField(max_length=10, required=True, null=False)
    worklocation = fields.StringField(max_length=10, required=True, null=False)
    projects = fields.EmbeddedDocumentListField(projects)
    skills = fields.EmbeddedDocumentListField(skills)
Exemplo n.º 21
0
class test_model(Document):
    email = fields.StringField(required=True)
    first_name = fields.StringField(max_length=50)
    last_name = fields.StringField(max_length=50)

    meta = {'ordering': ['-email']}
Exemplo n.º 22
0
class projects(EmbeddedDocument):
    projectId = fields.IntField(required=True, null=False)
    projectName = fields.StringField(max_length=10, required=True, null=False)
    startDate = fields.DateTimeField()
    endDate = fields.DateTimeField()
Exemplo n.º 23
0
class MongoSession(Document):
    session_key = fields.StringField(primary_key=True, max_length=40)
    session_data = fields.StringField()
    expire_date = fields.DateTimeField()

    meta = {'collection': 'django_session', 'allow_inheritance': False}
Exemplo n.º 24
0
class skills(EmbeddedDocument):
    technology = fields.StringField(max_length=50, required=True, null=False)
    exp = fields.StringField(max_length=50, required=True)
    level = fields.StringField(max_length=50, required=True)
Exemplo n.º 25
0
class Student(Document):
    student_code = fields.StringField(required=True)
    first_name = fields.StringField(required=True)
    last_name = fields.StringField(required=True)
    Major = fields.ReferenceField("Major", required=True)
Exemplo n.º 26
0
class Heal(Skill):
    def __str__(self):
        return 'Heal'

    regeneration_multiplier = fields.StringField()
Exemplo n.º 27
0
class UserRating(Document):
    user = fields.ReferenceField(User, reverse_delete_rule=CASCADE)
    description = fields.StringField(max_length=300)
    rating = fields.IntField(choices=[1, 2, 3, 4, 5], default=1)
    order = fields.ReferenceField(Order, reverse_delete_rule=CASCADE)
Exemplo n.º 28
0
class Tag(Document):
    name = fields.StringField(max_length=100)

    meta = {'collection': 'tags'}
Exemplo n.º 29
0
class BlogPost(Document):
    """A sample blog post document that will be indexed and searched. The title
    is more important than the content so should be weighted higher.
    """
    title = fields.StringField()
    content = fields.StringField()
Exemplo n.º 30
0
class DocumentEmbeddingDynamic(Document):
    name = fields.StringField()
    foo = fields.IntField()
    embedded = fields.EmbeddedDocumentField(DumbDynamicEmbedded)