Exemplo n.º 1
0
class BalanceTransaction(models.Model):
    amount = models.IntegerField(
        help_text=_('Gross amount of the transaction, in cents'), )
    available_on = models.DateTimeField(help_text=_(
        'The date the transaction’s net funds will become available in '
        'the Stripe balance.', ), )
    created = models.DateTimeField()
    currency = models.CharField(max_length=255, choices=CURRENCY_CHOICES)
    fee = models.IntegerField(help_text=_(
        'Fees (in cents) paid for this transaction', ), )
    fee_details = json.JSONField(help_text=_(
        'Detailed breakdown of fees (in cents) paid for this transaction', ), )
    net = models.IntegerField(help_text=_(
        'Net amount of the transaction, in cents.', ), )
    status = models.CharField(
        max_length=255,
        help_text=_(
            'If the transaction’s net funds are available in the Stripe '
            'balance yet. Either ``available`` or ``pending``.', ),
    )
    type = models.CharField(
        max_length=255,
        help_text=_(
            'Type of the transaction, one of: ``charge``, ``refund``, '
            '``adjustment``, ``application_fee``, ``application_fee_refund``, '
            '``transfer``, ``transfer_cancel`` or ``transfer_failure``.', ),
    )
    description = models.CharField(max_length=255)
    source = json.JSONField(help_text=_(
        'The Stripe object this transaction is related to.', ), )
    sourced_transfers = json.JSONField(help_text=_(
        'The transfers (if any) for which source is a source_transaction.', ),
                                       )
Exemplo n.º 2
0
class Post(models.Model):
    submission = json.JSONField()
    parent = json.JSONField()
    comment = json.JSONField()
    created = models.IntegerField()

    def comment_to_html(self):
        return parse_comment(self.comment.get('body'), display_images=True)

    def comment_img_src(self):
        match = re.search('http://.*\.jpg', self.comment.get('body'))
        if match:
            return match.group()

    def parent_as_title(self):
        if self.parent.get('body') != self.comment.get('body'):
            return parse_comment(self.parent.get('body'))
        else:
            return self.submission.get('title')

    def is_simple_image_post(self):
        return self.comment_img_src() is not None

    def get_context_url(self):
        link = self.submission.get('permalink')
        comment_id = self.comment.get('id')  #.split('_')[1]
        return "http://reddit.com/{}/{}/?context=2".format(link, comment_id)

    def __str__(self):
        return "%s -> %s" % (self.parent.get('body'), self.comment.get('body'))

    class Meta:
        ordering = ('-created', )
Exemplo n.º 3
0
class Riding(SlugMixin, NamesMixin, LinksMixin, models.Model):
    """
        ## Data sources

        * [Elections Canada's Electoral District Profiles (current ridings only)](http://www.elections.ca/Scripts/vis/SearchProvinces?L=e&PROV=CA&PROVID=99999&QID=-1&PAGEID=20)
        * [House of Common's Current Constituencies (current ridings only)](http://www.parl.gc.ca/Parliamentarians/en/constituencies)
        * [Library of Parliament's History of Federal Ridings](https://lop.parl.ca/About/Parliament/FederalRidingsHistory/hfer.asp?Language=E&Search=R)

        ## Notes

        * Some riding profile pages, from which we obtain historically related ridings, don't load properly (e.g. [Western Arctic](https://lop.parl.ca/About/Parliament/FederalRidingsHistory/hfer.asp?Include=Y&Language=F&Search=Det&rid=808). I've contacted [email protected] regarding these issues.

        ## Filtering examples

        * [Ridings in British Columbia](?slug__startswith=british-columbia-)
        * [Ridings named like Vancouver](?names__icontains=vancouver)
    """
    province = models.ForeignKey(Province, related_name="ridings")
    related_historically = models.ManyToManyField("self", blank=True)
    related_geographically = models.ManyToManyField("self", blank=True)
    electoral_district_number = models.PositiveIntegerField(null=True,
                                                            db_index=True)
    major_census_subdivisions = json.JSONField()
    area_km2 = models.PositiveIntegerField(null=True, db_index=True)
    postal_code_fsas = json.JSONField()
    current_parliamentarian = models.OneToOneField(Parliamentarian,
                                                   null=True,
                                                   related_name="riding",
                                                   db_index=True)

    class Meta:
        ordering = ("slug", )
Exemplo n.º 4
0
class PublicationBlock(SlugMixin, models.Model):
    """
        ## Data sources

        * [House of Commons' Hansard XML (39th Parliament onwards)](http://www.ourcommons.ca/Parliamentarians/en/PublicationSearch)

        ## Notes

        * TODO: Describe all the problems with the inconsistent data
    """
    CATEGORY_INTERVENTION = 1
    CATEGORY_WRITTEN_QUESTION = 2
    CATEGORY_WRITTEN_RESPONSE = 3
    CATEGORY_DIVISION = 4
    CATEGORY_MEMBERLIST = 5
    CATEGORY_ASIDES = 6
    CATEGORY_UNEXPECTED = 7

    sitting = models.ForeignKey(Sitting, null=True, db_index=True)
    committee = models.ForeignKey(Committee,
                                  related_name="publication_blocks",
                                  null=True,
                                  db_index=True)
    number = models.PositiveIntegerField(db_index=True)
    date_start = models.DateTimeField(db_index=True)
    metadata = json.JSONField()
    content = json.JSONField()
    name = models.CharField(max_length=200, db_index=True)
    parliamentarian = models.ForeignKey(parliament_models.Parliamentarian,
                                        related_name="publication_blocks",
                                        null=True,
                                        db_index=True)
    house_vote = models.OneToOneField(HouseVote,
                                      null=True,
                                      db_index=True,
                                      related_name="publication_block")
    previous = models.OneToOneField("self",
                                    null=True,
                                    blank=True,
                                    related_name="next",
                                    db_index=True)
    category = models.PositiveSmallIntegerField(choices=(
        (CATEGORY_INTERVENTION, "Intervention"),
        (CATEGORY_WRITTEN_QUESTION, "Written Question"),
        (CATEGORY_WRITTEN_RESPONSE, "Written Response"),
        (CATEGORY_DIVISION, "Division"),
        (CATEGORY_MEMBERLIST, "Member List"),
        (CATEGORY_ASIDES, "Asides"),
        (CATEGORY_UNEXPECTED, "Unexpected"),
    ))

    class Meta:
        unique_together = ("sitting", "committee", "number")
        ordering = ("date_start", )
Exemplo n.º 5
0
class HouseVote(SlugMixin, LinksMixin, models.Model):
    """
        ## Data sources

        * [House of Commons' Votes (38th Parliament onwards)](http://www.ourcommons.ca/parliamentarians/en/votes)
    """
    RESULT_NEGATIVED = 1
    RESULT_AGREED_TO = 2
    RESULT_TIE = 3

    sitting = models.ForeignKey(Sitting,
                                related_name="house_votes",
                                db_index=True)
    number = models.PositiveSmallIntegerField(db_index=True)
    bill = models.ForeignKey(Bill,
                             blank=True,
                             null=True,
                             related_name="house_votes",
                             db_index=True)
    context = json.JSONField()
    result = models.PositiveSmallIntegerField(choices=(
        (RESULT_NEGATIVED, "Negatived"),
        (RESULT_AGREED_TO, "Agreed To"),
        (RESULT_TIE, "Tie"),
    ),
                                              db_index=True)

    class Meta:
        ordering = ("sitting__date", "slug")
Exemplo n.º 6
0
class TransferReversal(models.Model):
    """Stripe Transfer Reversal object.

    A previously created transfer can be reversed if it has not yet been paid
    out. Funds will be refunded to your available balance, and the fees you
    were originally charged on the transfer will be refunded. You may not
    reverse automatic Stripe transfers.
    """

    amount = models.IntegerField(help_text=_('Amount reversed, in cents.'))
    created = models.DateTimeField()
    currency = models.CharField(
        max_length=255,
        choices=CURRENCY_CHOICES,
        help_text=_(
            'Three-letter ISO code representing the currency of the reversal.',
        ),
    )
    balance_transaction = models.ForeignKey(
        'BalanceTransaction',
        help_text=_(
            'Balance transaction that describes the impact of this reversal '
            'on your account balance.', ),
        related_name='transfer_reversal_balance_transaction',
        on_delete=models.CASCADE,
    )
    metadata = json.JSONField(help_text=_(
        'A set of key/value pairs that you can attach to a charge object. '
        'it can be useful for storing additional information about the '
        'transfer reversal in a structured format.', ), )
    transfer = models.ForeignKey(
        'Transfer',
        help_text=_('ID of the transfer that was reversed.'),
        on_delete=models.CASCADE,
    )
class ApplicationFeeRefund(models.Model):
    """Stripe Application Fee Refund object.

    Application Fee Refund objects allow you to refund an application fee that
    has previously been created but not yet refunded. Funds will be refunded to
    the Stripe account that the fee was originally collected from.
    """

    amount = models.IntegerField(help_text=_('Amount reversed, in cents.'))
    created = models.DateTimeField()
    currency = models.CharField(
        max_length=255,
        help_text=_(
            'Three-letter ISO currency code representing the currency of the '
            'reverse.', ),
        choices=CURRENCY_CHOICES,
    )
    balance_transaction = models.ForeignKey(
        'BalanceTransaction',
        help_text=_(
            'Balance transaction that describes the impact of this reversal '
            'on your account balance.', ),
        on_delete=models.CASCADE,
    )
    fee = models.ForeignKey(
        'ApplicationFee',
        help_text=_('ID of the application fee that was refunded.'),
        on_delete=models.CASCADE,
    )
    metadata = json.JSONField(help_text=_(
        'A set of key/value pairs that you can attach to a charge object. '
        'it can be useful for storing additional information about the '
        'charge in a structured format.', ), )
Exemplo n.º 8
0
class BankAccount(PaymentMethod):
    account = models.ForeignKey('account', on_delete=models.CASCADE)
    account_holder_name = models.CharField(max_length=255)
    account_holder_type = models.CharField(
        max_length=255,
        choices=BANK_ACCOUNT_TYPES,
    )
    bank_name = models.CharField(max_length=255)
    country = models.CharField(  # todo: add CHOICES
        max_length=255, )
    currency = models.CharField(max_length=255, choices=CURRENCY_CHOICES)
    customer = models.ForeignKey('Customer', on_delete=models.CASCADE)
    default_for_currency = models.BooleanField()
    fingerprint = models.CharField(max_length=255)
    last4 = models.CharField(max_length=4)
    metadata = json.JSONField()
    routing_number = models.CharField(max_length=255)
    status = models.CharField(max_length=255, choices=BANK_ACCOUNT_STATUS)

    @classmethod
    def from_stripe_object(cls, stripe_object, customer):
        _dict = stripe_object.to_dict()
        _dict.pop('object')
        _dict.pop('account')
        if 'customer' in _dict:
            _dict.pop('customer')
        _dict['customer'] = customer

        account = stripe.Account.retrieve(stripe_object.account)
        _dict['account'] = Account.from_stripe_object(account)
        c = cls(**_dict)
        c.save()

        return c
Exemplo n.º 9
0
class Engagement(TimeStampedModel):
    user = ForeignKey(User, related_name="engagements")
    assignment = ForeignKey(Assignment, related_name="engagements")
    field_data = json.JSONField(blank=True, null=True)

    def __unicode__(self):
        return "%s is engaging %s" % (self.user, self.assignment.worksheet)
Exemplo n.º 10
0
class Parliamentarian(SlugMixin, NamesMixin, LinksMixin, models.Model):
    """
        ## Data sources

        * [OpenParliament.ca (1994 onwards)](https://openparliament.ca/politicians/)
        * [House of Commons' Members of Parliament](http://www.parl.gc.ca/Parliamentarians/en/members)
        * [Library of Parliament's History of Federal Ridings](https://lop.parl.ca/About/Parliament/FederalRidingsHistory/hfer.asp?Language=E&Search=C)
    """
    photo = models.ImageField(upload_to=get_photo_path)
    birthdate = models.CharField(
        max_length=10,
        db_index=True,
        help_text=
        "Exact birth dates for parliamentarians in the 1800s sometimes omitted day or month"
    )
    lop_item_code = models.SlugField(db_index=True, unique=True)
    constituency_offices = json.JSONField()
    hill_phone = models.CharField(max_length=20, db_index=True)
    hill_fax = models.CharField(max_length=20, db_index=True)

    LANG_EN = 1
    LANG_FR = 2
    LANG_BOTH = 3
    preferred_language = models.PositiveSmallIntegerField(choices=(
        (LANG_EN, "English"),
        (LANG_FR, "Français"),
        (LANG_BOTH, "English / Français"),
    ),
                                                          null=True,
                                                          db_index=True)

    class Meta:
        ordering = ("slug", )
Exemplo n.º 11
0
class SubscriptionItem(models.Model):

    id = models.CharField(max_length=255, primary_key=True)
    created = UnixDateTimeField()
    plan = models.ForeignKey(
        'Plan',
        on_delete=models.CASCADE,
        null=True,
    )

    subscription = models.ForeignKey(
        'Subscription',
        on_delete=models.CASCADE,
        null=True,
    )
    metadata = json.JSONField()
    proration_date = UnixDateTimeField(null=True)
    prorate = models.NullBooleanField(null=True)
    quantity = models.IntegerField(null=True)

    @classmethod
    def from_stripe_object(cls, stripe_object, customer=None):
        _dict = stripe_object.to_dict()
        _dict.pop('object')

        _dict = get_customer_info(_dict, customer)

        if 'plan' in _dict:
            _dict['plan'] = Plan.from_stripe_object(_dict.pop('plan'))

        s = cls(**_dict)
        s.save()
        return s
Exemplo n.º 12
0
Arquivo: job.py Projeto: agpar/Rodan
class Job(models.Model):
    """
        A Job represents a task that may be placed in a workflow. When a job is placed
        in a workflow, some of the fields are copied over into a `WorkflowJob`. When a
        workflow is run, these workflowjobs are "frozen" as RunJobs, so that previous runs
        of a workflow may be viewed.

        When Rodan starts up, any jobs defined in the jobs/ directory are loaded into the database
        using this model. All jobs must conform to the same "protocol;" that is, they must define:

        1. input_types: The pixel types for images that may be processed by this job.
        2. output_types: The pixel types that may be produced by this job.
        3. settings: An array of settings that, at a minimum conform to the following structure:
            {
                default: "-1.0",          The default value of the setting. Also used as the runtime value.
                has_default: true,        Whether this has a default value or not. Settings that accept numeric arguments usually have a default.
                name: "noise_variance",   The setting's name. Used both for display, as well as the keyword argument.
                type: "real"              The value type. Could be "real" or "int", etc...
            }

        Interactive jobs must have an interface defined for the interactive part.

        Additionally, a job must define its Category, which is used to group and organize the jobs in the
        Gamera interface. Optionally, a `description` field may give documentation about the job, and an `author`
        can give information about who was responsible for writing the job.

        More information about jobs and their execution may be found in the __init__.py of the jobs/ directory.
    """
    uuid = UUIDField(primary_key=True, auto=True)
    job_name = models.CharField(max_length=255)
    author = models.CharField(max_length=255, blank=True, null=True)
    category = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)

    input_types = json.JSONField(blank=True, null=True)
    output_types = json.JSONField(blank=True, null=True)
    settings = json.JSONField(blank=True, null=True)

    enabled = models.BooleanField(default=False)
    interactive = models.BooleanField(default=False)

    def __unicode__(self):
        return u"<Job {0}>".format(self.job_name)

    class Meta:
        app_label = 'rodan'
        ordering = ['category']
Exemplo n.º 13
0
class Plan(models.Model):
    """Stripe Plan object.

    A subscription plan contains the pricing information for different products
    and feature levels on your site. For example, you might have a $10/month
    plan for basic features and a different $20/month plan for premium
    features.
    """
    id = models.CharField(max_length=255, primary_key=True)
    livemode = models.BooleanField()
    amount = models.PositiveIntegerField(help_text=_(
        'The amount in cents to be charged on the interval specified', ), )
    created = UnixDateTimeField()
    currency = models.CharField(
        max_length=255,
        choices=CURRENCY_CHOICES,
        help_text=_('Currency in which the subscription will be charged', ),
    )
    interval = models.CharField(
        choices=PLAN_INTERVAL_CHOICES,
        max_length=255,
        help_text=_(
            'One of ``day``, ``week``, ``month`` or ``year``. The frequency '
            'with which a subscription should be billed.', ),
    )
    interval_count = models.PositiveIntegerField(help_text=_(
        'The number of intervals (specified in the ``interval`` property) '
        'between each subscription billing. For example, '
        '``interval=month`` and interval_count=3 bills every 3 months.', ), )
    name = models.CharField(
        max_length=255,
        help_text=_('Display name of the plan', ),
    )
    metadata = json.JSONField(help_text=_(
        'A set of key/value pairs that you can attach to a charge object. '
        'it can be useful for storing additional information about the '
        'plan in a structured format.', ), )
    trial_period_days = models.PositiveIntegerField(
        help_text=_(
            'Number of trial period days granted when subscribing a customer '
            'to this plan. Null if the plan has no trial period.', ),
        null=True,
    )
    statement_descriptor = models.CharField(
        max_length=255,
        help_text=_(
            'Extra information about a charge for the customer’s credit card '
            'statement.', ),
        null=True,
    )

    @classmethod
    def from_stripe_object(cls, stripe_object):
        _dict = stripe_object.to_dict()
        _dict.pop('object')

        s = cls(**_dict)
        s.save()
        return s
Exemplo n.º 14
0
class Event(models.Model):
    """Stripe Event object.

    Events are our way of letting you know about something interesting that has
    just happened in your account. When an interesting event occurs, we create
    a new event object. For example, when a charge succeeds we create a
    ``charge.succeeded`` event; or, when an invoice can't be paid we create an
    ``invoice.payment_failed`` event. Note that many API requests may cause
    multiple events to be created. For example, if you create a new
    subscription for a customer, you will receive both a
    ``customer.subscription.created`` event and a ``charge.succeeded`` event.

    Like our other API resources, you can retrieve an individual event or a
    list of events from the API. We also have a system for sending the events
    directly to your server, called webhooks. Webhooks are managed in your
    account settings, and our webhook guide will help you get them set up.

    NOTE: Right now, we only guarantee access to events through the Retrieve
    Event API for 30 days.
    """
    id = models.CharField(max_length=255, primary_key=True)
    livemode = models.BooleanField()
    created = UnixDateTimeField()
    data = json.JSONField(help_text=_(
        'Hash containing data associated with the event.', ), )
    pending_webhooks = models.PositiveIntegerField(help_text=_(
        'Number of webhooks yet to be delivered successfully (return a '
        '20x response) to the URLs you’ve specified.', ), )
    type = models.CharField(
        max_length=255,
        help_text=_(
            'Description of the event: e.g. invoice.created, charge.refunded, '
            'etc.', ),
        choices=EVENT_TYPES,
    )
    api_version = models.CharField(
        max_length=255,
        help_text=_(
            'The Stripe API version used to render data. Note: this property '
            'is populated for events on or after October 31, 2014.', ),
    )
    request = models.CharField(
        max_length=255,
        help_text=_(
            'ID of the API request that caused the event. If null, the event '
            'was automatic (e.g. Stripe’s automatic subscription handling). '
            'Request logs are available in the dashboard but currently not in '
            'the API. Note: this property is populated for events on or after '
            'April 23, 2013.', ),
    )

    @classmethod
    def from_stripe_object(cls, stripe_object):
        _dict = stripe_object.to_dict()
        _dict.pop('object')

        s = cls(**_dict)
        s.save()
        return s
Exemplo n.º 15
0
class Worksheet(ContentModel):
    instructions = TextField(blank=True, null=True)
    background = ImageField(upload_to="lessons/worksheets/backgrounds/")
    field_data = json.JSONField(blank=True, null=True)
    related_content = ManyToManyField(RelatedContent,
                                      blank=True,
                                      null=True,
                                      related_name='worksheets')
Exemplo n.º 16
0
class Recording(SlugMixin, NamesMixin, LinksMixin, models.Model):
    """
        ## Data sources

        * [ParlVU (39th Parliament onwards)](http://parlvu.parl.gc.ca/)

        ## Notes

        * OurCommons and ParlVU don't always agree. I've identified the following inconsistencies and contacted [email protected]. I'm currently waiting on a response.
          * (Legitimate discrepency) ParlVU speaks of [HoC Sitting No. 76 (2016-06-17)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20160617/-1/25343), but OurCommons thinks [#75 is on 2016-06-17](http://www.ourcommons.ca/DocumentViewer/en/42-1/house/sitting-75/order-notice) and [#76 is on 2016-09-19](http://www.ourcommons.ca/DocumentViewer/en/42-1/house/sitting-76/order-notice).
          * (Split event) ParlVU speaks of [HoC Sitting No. A-50 (2010-05-27)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20100527/-1/18261), but OurCommons thinks [#50 is on 2010-05-27](http://www.ourcommons.ca/DocumentViewer/en/40-3/house/sitting-50/order-notice) and #50A doesn't exist.
          * (Split event) ParlVU speaks of [HoC Sitting No. A-98 (2008-05-26)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20080526/-1/24242), but OurCommons thinks [#98 is on 2008-05-26](http://www.ourcommons.ca/DocumentViewer/en/39-2/house/sitting-98/order-notice) and #98A doesn't exist.
          * (Split event) ParlVU speaks of [HoC Sitting No. A-13 (2008-12-04)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20081204/-1/18081), but OurCommons thinks [#13 is on 2008-12-04](http://www.ourcommons.ca/DocumentViewer/en/40-1/house/sitting-13/order-notice) and #13A doesn't exist.
          * (Split event) ParlVU speaks of [HoC Sitting No. A-36 (2007-12-12)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20071212/-1/24179), but OurCommons thinks [#36 is on 2007-12-12](http://www.ourcommons.ca/DocumentViewer/en/39-2/house/sitting-36/order-notice) and #36A doesn't exist.
          * (Special sitting with no publications) ParlVU speaks of [HoC Sitting No. 888 (2006-09-22)](http://parlvu.parl.gc.ca/XRender/en/PowerBrowser/PowerBrowserV2/20060922/-1/24055), but OurCommons thinks [#51 is on 2006-09-22](http://www.ourcommons.ca/DocumentViewer/en/39-1/house/sitting-51/order-notice) and #888 doesn't exist.
        * [CPAC's Video Archive](http://www.cpac.ca/en/video-archive/) is a good resource for other recordings (e.g. news conferences, television appearances, parliamentary videos prior to the 39th parliament, etc).
    """
    CATEGORY_AUDIO_ONLY = 1
    CATEGORY_TELEVISED = 2
    CATEGORY_IN_CAMERA = 2
    CATEGORY_NO_BROADCAST = 3
    CATEGORY_TRAVEL = 4
    STATUS_ADJOURNED = 1
    STATUS_CANCELLED = 2
    STATUS_NOT_STARTED = 3

    scheduled_start = models.DateTimeField(db_index=True)
    scheduled_end = models.DateTimeField(db_index=True)
    actual_start = models.DateTimeField(null=True, db_index=True)
    actual_end = models.DateTimeField(null=True, db_index=True)
    location = json.JSONField()
    category = models.PositiveSmallIntegerField(choices=(
        (CATEGORY_AUDIO_ONLY, "Audio only"),
        (CATEGORY_TELEVISED, "Televised"),
        (CATEGORY_IN_CAMERA, "In Camera"),
        (CATEGORY_NO_BROADCAST, "No Broadcast"),
        (CATEGORY_TRAVEL, "Travel"),
    ),
                                                db_index=True)
    status = models.PositiveSmallIntegerField(choices=(
        (STATUS_ADJOURNED, "Adjourned"),
        (STATUS_CANCELLED, "Cancelled"),
        (STATUS_NOT_STARTED, "Not Started"),
    ),
                                              db_index=True)
    committee = models.ForeignKey(Committee,
                                  null=True,
                                  blank=True,
                                  related_name="recordings",
                                  db_index=True)
    sitting = models.ForeignKey(Sitting,
                                null=True,
                                blank=True,
                                related_name="recordings",
                                db_index=True)

    class Meta:
        ordering = ("scheduled_start", "slug")
Exemplo n.º 17
0
class Balance(models.Model):
    """Stripe Balance object.

    This is an object representing your Stripe balance. You can retrieve it to
    see the balance currently on your Stripe account.

    You can also retrieve a list of the balance history, which contains a full
    list of transactions that have ever contributed to the balance (charges,
    refunds, transfers, and so on).
    """

    livemode = models.BooleanField()
    available = json.JSONField(help_text=_(
        'Funds that are available to be paid out automatically by '
        'Stripe or explicitly via the transfers API.', ), )
    pending = json.JSONField(help_text=_(
        'Funds that are not available in the balance yet, due to the '
        '7-day rolling pay cycle.', ), )
Exemplo n.º 18
0
class LinksMixin(models.Model):
    links = json.JSONField()

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.links = self.links or {EN: {}, FR: {}}
Exemplo n.º 19
0
class Assessment(TimeStampedModel):
    assessor = ForeignKey(User, related_name="assessment")
    engagement = ForeignKey(Engagement, related_name="assessments")
    field_data = json.JSONField(blank=True, null=True)
    notes = TextField(blank=True, null=True)
    points_awarded = FloatField(default=0.0)
    has_awarded = BooleanField(default=False)

    def __unicode__(self):
        return "%s assessed %s on %s" % (self.assessor, self.engagement.user,
                                         self.engagement.assignment.worksheet)
Exemplo n.º 20
0
class WorkflowJob(models.Model):
    """
        A WorkflowJob is a Job object that has been added to a workflow.

        WorkflowJobs may be interactive or non-interactive. An interactive job will present
        users with an interface for performing a unit of work; for example, cropping or rotating a page,
        or confirming an operation before the image can proceed to the next job.

        Non-interactive jobs do not require human input (e.g., converting an RGB image to greyscale) and
        as such may be executed automatically.
    """
    WORKFLOW_JOB_TYPES = (
        (0, "Non-Interactive"),
        (1, "Interactive")
    )

    uuid = UUIDField(primary_key=True, auto=True)
    workflow = models.ForeignKey(Workflow, related_name="workflow_jobs", blank=True, null=True)
    job = models.ForeignKey(Job)
    sequence = models.IntegerField(blank=True, null=True)
    job_type = models.IntegerField(choices=WORKFLOW_JOB_TYPES, default=0)
    job_settings = json.JSONField(default="[]", blank=True, null=True)

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return u"<WorkflowJob {0}>".format(str(self.uuid))

    class Meta:
        app_label = 'rodan'
        ordering = ('sequence',)

    @property
    def job_name(self):
        return self.job.job_name

    @property
    def job_description(self):
        return self.job.description

    @property
    def input_pixel_types(self):
        return self.job.input_types["pixel_types"]

    @property
    def output_pixel_types(self):
        return self.job.output_types["pixel_types"]
Exemplo n.º 21
0
class VersionActivity(models.Model):
    """
    A metadata class to link an Action with a Revision
    """
    revision = models.ForeignKey(reversion.models.Revision)
    action = models.OneToOneField(Action, related_name='version')
    diffs = json.JSONField()
    checked_by = models.ForeignKey(User, null=True, blank=True)
    checked_on = models.DateTimeField(blank=True, null=True)
    
    def diffs_html(self):
      """
      Outputs the "diffs" field as an HTML report
      """
      dmp = diff_match_patch()
      return dmp.diff_prettyHtml(self.diffs)
Exemplo n.º 22
0
class Source(models.Model):
    id = models.CharField(max_length=255, primary_key=True)
    amount = models.PositiveIntegerField()
    client_secret = models.CharField(max_length=255)
    code_verification = json.JSONField()
    created = UnixDateTimeField()
    currency = models.CharField(
        max_length=255,
        choices=CURRENCY_CHOICES,
        help_text=_('Currency in which the subscription will be charged', ),
    )
    customer = models.ForeignKey(
        'Customer',
        on_delete=models.CASCADE,
        null=True,
    )
    flow = models.CharField(
        choices=FLOW_CHOICES,
        max_length=24,
    )
    livemode = models.BooleanField()
    metadata = json.JSONField()
    owner = json.JSONField()
    receiver = json.JSONField()
    redirect = json.JSONField()
    statement_descriptor = models.CharField(max_length=255, )
    status = models.CharField(
        max_length=255,
        choices=SOURCE_STATUS_CHOICES,
    )
    type = models.CharField(
        max_length=255,
        choices=SOURCE_TYPE_CHOICES,
    )
    usage = models.CharField(
        max_length=255,
        choices=SOURCE_USAGE_CHOICES,
    )
    bitcoin = json.JSONField()

    @classmethod
    def from_stripe_object(cls, stripe_object, customer=None):
        _dict = stripe_object.to_dict()
        _dict.pop('object')

        if customer:
            if 'customer' in _dict:
                _dict.pop('customer')
            _dict['customer'] = customer

        s = Source(**_dict)
        s.save()
        return s
Exemplo n.º 23
0
class Stats(models.Model):
    """
    An abstract base class to hold statistics about a
    subject or discipline.
    """

    division_set = models.ForeignKey(DivisionSet)
    letter_grades = models.IntegerField(default=0)
    mean = models.FloatField(null=True)
    stdev = models.FloatField(null=True)
    distribution = json.JSONField(null=True)
    my_rank = models.IntegerField(default=0)
    rank_count = models.IntegerField(default=0)

    class Meta:
        abstract = True

    @property
    def formatted_distribution(self):
        return utils.format_distribution(self.distribution, self.letter_grades)
Exemplo n.º 24
0
class Section(models.Model):
    """
    A particular term's offering of a course, with a unique CCN.
    """
    course = models.ForeignKey(Course)
    term = models.ForeignKey(Term)
    number = models.CharField(max_length=10)
    instructor = models.CharField(max_length=1024)
    ccn = models.CharField(max_length=5, verbose_name="CCN")

    # Stats
    distribution = json.JSONField(null=True)
    letter_grades = models.IntegerField(default=0)
    mean = models.FloatField(null=True)
    stdev = models.FloatField(null=True)

    def __unicode__(self):
        return "{0}-{1} ({2})".format(self.course, self.number, self.term)

    class Meta:
        ordering = ['term', 'number']
Exemplo n.º 25
0
class DivisionSet(models.Model):
    name = models.CharField(max_length=256)
    slug = models.SlugField(default='')
    # data is a json field consisting exactly of
    # { 'divisions' : [ list of divisions ] }
    data = json.JSONField()

    def __unicode__(self):
        return self.name

    @property
    def divisions_verbose(self):
        return [
            Course.DIVISION_CHOICE_DICT[div] for div in self.data['divisions']
        ]

    @property
    def divisions_str(self):
        return ', '.join(self.divisions_verbose)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(DivisionSet, self).save(*args, **kwargs)
Exemplo n.º 26
0
class Interaction(models.Model):
    VERB_VIEWED = 'viewed'
    VERB_LIKED = 'liked'
    VERB_MESSAGED = 'messaged'
    VERB_CHOICES = (
        (VERB_VIEWED, _('Viewed')),
        (VERB_LIKED, _('Liked')),
        (VERB_MESSAGED, _('Messaged')),
    )

    sender = models.ForeignKey(User, related_name='sent_interactions')
    verb = models.CharField(max_length=16, choices=VERB_CHOICES)
    receiver = models.ForeignKey(User, related_name='received_interactions')
    extra = json.JSONField(blank=True)

    class Meta:
        index_together = (
            ('verb', 'sender'),
            ('verb', 'receiver'),
        )

    def __unicode__(self):
        return '%s %s %s' % (self.sender, self.verb, self.receiver)
Exemplo n.º 27
0
class Transfer(models.Model):
    """Stripe Transfer object.

    When Stripe sends you money or you initiate a transfer to a bank account,
    debit card, or connected Stripe account, a transfer object will be created.
    You can retrieve individual transfers as well as list all transfers.

    View the `documentation` on creating transfers via the API.

    .. _documentation: https://stripe.com/docs/tutorials/sending-transfers
    """

    livemode = models.BooleanField()
    amount = models.IntegerField(help_text=_(
        'Amount (in cents) to be transferred to your bank account', ), )
    created = models.DateTimeField(help_text=_(
        'Time that this record of the transfer was first created.', ), )
    currency = models.CharField(
        max_length=255,
        choices=CURRENCY_CHOICES,
        help_text=_(
            'Three-letter ISO code representing the currency of the transfer.',
        ),
    )
    date = models.DateTimeField(help_text=_(
        'Date the transfer is scheduled to arrive in the bank. This '
        'doesn’t factor in delays like weekends or bank holidays.', ), )
    reversals = json.JSONField(help_text=_(
        'A list of reversals that have been applied to the transfer.', ), )
    reversed = models.BooleanField(help_text=_(
        'Whether or not the transfer has been fully reversed. If the '
        'transfer is only partially reversed, this attribute will still '
        'be false.', ), )

    status = models.CharField(
        max_length=255,
        help_text=_(
            'Current status of the transfer (``paid``, ``pending``, '
            '``canceled`` or ``failed``). A transfer will be ``pending`` '
            'until it is submitted, at which point it becomes ``paid``. If it '
            'does not go through successfully, its status will change to '
            '``failed`` or ``canceled``.', ),
        choices=TRANSFER_STATUS_CHOICES,
    )
    type = models.CharField(
        max_length=255,
        help_text=_(
            'The type of this type of this transfer. Can be ``card``, '
            '``bank_account``, or ``stripe_account``.', ),
        choices=TRANSFER_TYPE_CHOICES,
    )
    amount_reversed = models.IntegerField(help_text=_(
        'Amount in cents reversed (can be less than the amount attribute '
        'on the transfer if a partial reversal was issued).', ), )
    balance_transaction = models.ForeignKey(
        'BalanceTransaction',
        help_text=_(
            'Balance transaction that describes the impact of this transfer '
            'on your account balance.', ),
        on_delete=models.CASCADE,
    )
    description = models.TextField(
        help_text=_('Internal-only description of the transfer'))
    failure_code = models.CharField(
        max_length=255,
        help_text=_(
            'Error code explaining reason for transfer failure if available. '
            'See Types of transfer failures for a list of failure codes.', ),
        choices=TRANSFER_FAILURE_CHOICES,
    )
    failure_message = models.TextField(help_text=_(
        'Message to user further explaining reason for transfer failure '
        'if available.', ), )
    metadata = json.JSONField(help_text=_(
        'A set of key/value pairs that you can attach to a charge object. '
        'it can be useful for storing additional information about the '
        'transfer in a structured format.', ), )
    application_fee = models.CharField(max_length=255)
    destination = models.CharField(
        max_length=255,
        help_text=_(
            'ID of the bank account, card, or Stripe account the transfer was '
            'sent to.', ),
    )
    destination_payment = models.CharField(
        max_length=255,
        help_text=_(
            'If the destination is a Stripe account, this will be the ID of '
            'the payment that the destination account received for the '
            'transfer.', ),
    )
    source_transaction = models.CharField(
        max_length=255,
        help_text=_(
            'ID of the charge (or other transaction) that was used to fund '
            'the transfer. If null, the transfer was funded from the '
            'available balance.', ),
    )
    statement_descriptor = models.CharField(
        max_length=255,
        help_text=_(
            'Extra information about a transfer to be displayed on the user’s '
            'bank statement.', ),
    )
Exemplo n.º 28
0
class Course(models.Model):
    """
    A single course belonging to a single division, with
    many sections offered over multiple terms.
    """
    LOWER = 0
    UPPER = 1
    GRADUATE = 2
    TEACHING = 3
    PROFESSIONAL = 4
    MASTERS = 5
    DOCTORAL = 6
    OTHER = 7
    DIVISION_CHOICES = ((LOWER, "Lower Division"), (UPPER, "Upper Division"),
                        (GRADUATE, "Graduate"), (TEACHING, "Teaching"),
                        (PROFESSIONAL, "Professional"), (MASTERS,
                                                         "Master's Exam"),
                        (DOCTORAL, "Doctoral Exam"), (OTHER, "Other"))
    DIVISION_CHOICE_DICT = dict(DIVISION_CHOICES)

    subject = models.ForeignKey(Subject)
    title = models.TextField()
    number = models.CharField(max_length=10)
    num_numerical_part = models.IntegerField(null=True)
    division = models.IntegerField(choices=DIVISION_CHOICES, default=OTHER)

    # Stats
    distribution = json.JSONField(null=True)
    letter_grades = models.IntegerField(default=0)
    mean = models.FloatField(null=True)
    stdev = models.FloatField(null=True)

    def __unicode__(self):
        return "{0} {1}".format(self.subject, self.number)

    @property
    def formatted_distribution(self):
        return utils.format_distribution(self.distribution, self.letter_grades)

    def save(self, *args, **kwargs):
        m = course_num_pattern.match(self.number)
        if m:
            self.num_numerical_part = int(m.group(1))
            if self.num_numerical_part < 100:
                self.division = self.LOWER
            elif self.num_numerical_part < 200:
                self.division = self.UPPER
            elif self.num_numerical_part < 300:
                self.division = self.GRADUATE
            elif self.num_numerical_part < 400:
                self.division = self.TEACHING
            elif self.num_numerical_part < 500:
                self.division = self.PROFESSIONAL
            elif self.num_numerical_part == 601:
                self.division = self.MASTERS
            elif self.num_numerical_part == 602:
                self.division = self.DOCTORAL
            else:
                self.division = self.OTHER
        else:
            self.division = self.OTHER
        super(Course, self).save(*args, **kwargs)

    class Meta:
        ordering = ['subject', 'num_numerical_part', 'number']
Exemplo n.º 29
0
class BitCoinReceiver(models.Model):
    """Stripe Bitcoin Receiver object.

    A Bitcoin receiver wraps a Bitcoin address so that a customer can push a
    payment to you. This `guide`_ describes how to use receivers to create
    Bitcoin payments.

    .. _guide: https://stripe.com/docs/guides/bitcoin
    """

    livemode = models.BooleanField()
    active = models.BooleanField(help_text=_(
        'True when this bitcoin receiver has received a non-zero amount '
        'of bitcoin.', ), )
    amount = models.PositiveIntegerField(help_text=_(
        'The amount of currency that you are collecting as payment.', ), )
    amount_received = models.PositiveIntegerField(help_text=_(
        'The amount of currency to which bitcoin_amount_received has been '
        'converted.', ), )
    bitcoin_amount = models.PositiveIntegerField(help_text=_(
        'The amount of bitcoin that the customer should send to fill the '
        'receiver. The bitcoin_amount is denominated in Satoshi: there '
        'are 10^8 Satoshi in one bitcoin.', ), )
    bitcoin_amount_received = models.PositiveIntegerField(help_text=_(
        'The amount of bitcoin that has been sent by the customer to this '
        'receiver.', ), )
    bitcoin_uri = models.URLField(help_text=_(
        'This URI can be displayed to the customer as a clickable link '
        '(to activate their bitcoin client) or as a QR code (for mobile '
        'wallets).', ), )
    created = models.DateTimeField()
    currency = models.CharField(
        max_length=255,
        help_text=_(
            'Three-letter ISO currency code representing the currency to '
            'which the bitcoin will be converted.', ),
        choices=CURRENCY_CHOICES,
    )
    filled = models.BooleanField(help_text=_(
        'This flag is initially false and updates to true when the '
        'customer sends the bitcoin_amount to this receiver.', ), )
    inbound_address = models.CharField(
        max_length=255,
        help_text=_(
            'A bitcoin address that is specific to this receiver. The '
            'customer can send bitcoin to this address to fill the receiver.',
        ),
    )
    transactions = json.JSONField(help_text=_(
        'A list with one entry for each time that the customer sent '
        'bitcoin to the receiver. Hidden when viewing the receiver with a '
        'publishable key.', ), )
    uncaptured_funds = models.BooleanField(help_text=_(
        'This receiver contains uncaptured funds that can be used for a '
        'payment or refunded.', ), )
    description = models.CharField(max_length=255)
    email = models.EmailField(help_text=_(
        'The customer’s email address, set by the API call that creates '
        'the receiver.', ), )
    metadata = json.JSONField(help_text=_(
        'A set of key/value pairs that you can attach to a charge object. '
        'it can be useful for storing additional information about the '
        'charge in a structured format.', ), )
    payment = models.CharField(
        max_length=255,
        help_text=_(
            'The ID of the payment created from the receiver, if any. Hidden '
            'when viewing the receiver with a publishable key.', ),
    )
    refund_address = models.CharField(
        max_length=255,
        help_text=_(
            'The refund address for these bitcoin, if communicated by the '
            'customer.', ),
    )
    customer = models.ForeignKey(
        'Customer',
        on_delete=models.CASCADE,
    )
Exemplo n.º 30
0
class Refund(models.Model):

    """Stripe Refund objects.

    Refund objects allow you to refund a charge that has previously been
    created but not yet refunded. Funds will be refunded to the credit or debit
    card that was originally charged. The fees you were originally charged are
    also refunded.
    """
    id = models.CharField(max_length=255, primary_key=True)
    amount = models.IntegerField(help_text=_('Amount reversed, in cents.'))
    created = UnixDateTimeField()
    currency = models.CharField(
        max_length=3,
        help_text=_(
            'Three-letter ISO code representing the currency of the reversal.',
        ),
    )
    balance_transaction = models.CharField(
        max_length=255,
        help_text=_(
            'Balance transaction that describes the impact of this reversal '
            'on your account balance.',
        ),
    )
    charge = models.ForeignKey(
        'Charge',
        help_text=_(
            'ID of the charge that was ',
        ),
        on_delete=models.CASCADE,
    )
    metadata = json.JSONField(
        help_text=_(
            'A set of key/value pairs that you can attach to a charge object. '
            'It can be useful for storing additional information about the '
            'refund in a structured format.',
        ),
    )
    reason = models.CharField(
        max_length=255,
        choices=REFUND_CHOICES,
        help_text=_(
            'Reason for the refund. If set, possible values are duplicate, '
            'fraudulent, and requested_by_customer.',
        ),
    )
    receipt_number = models.CharField(
        max_length=255,
        help_text=_(
            'This is the transaction number that appears on email receipts '
            'sent for this refund.',
        ),
    )
    status = models.CharField(
        max_length=255,
        choices=REFUND_STATUS_CHOICES,
    )
    description = models.CharField(max_length=255)

    @classmethod
    def from_stripe_object(cls, stripe_object, charge=None):
        _dict = stripe_object.to_dict()
        _dict.pop('object')
        _dict.pop('charge')

        if charge:
            _dict['charge'] = charge
        else:
            Charge = cls.charge.field.related_model
            _dict['charge'] = Charge.from_stripe_object(
                stripe.Charge.retrieve(stripe_object.charge),
                descend=False,
            )

        s = cls(**_dict)
        s.save()
        return s