コード例 #1
0
def test_sale_with_discount(client, sale_payload, store):
    sale_payload['products'][0]['quantity'] = 10
    sale_payload['payments'][0]['value'] = 100
    sale_payload['discount_value'] = 25

    response = client.post('/sale', json=sale_payload)

    sale = store.find(Sale).order_by(Desc(Sale.open_date)).first()

    assert response.status_code == 201
    assert sale.get_total_sale_amount() == currency('75')
    assert sale.discount_value == currency('25')
コード例 #2
0
 def translators(self):
     """See `ILanguage`."""
     from lp.registry.model.person import (
         Person,
         PersonLanguage,
     )
     return IStore(Language).using(
         Join(Person, LanguageSet._getTranslatorJoins(),
              Person.id == PersonLanguage.personID), ).find(
                  Person,
                  PersonLanguage.language == self,
              ).order_by(Desc(KarmaCache.karmavalue))
コード例 #3
0
 def test_limitsGroupedByOrderDirection(self):
     # limitsGroupedByOrderDirection() returns a sequence of
     # (expressions, memos), where expressions is a list of
     # ORDER BY expressions which either are all instances of
     # PropertyColumn, or are all instances of Desc(PropertyColumn).
     # memos are the related limit values.
     resultset = self.makeStormResultSet()
     range_factory = StormRangeFactory(resultset, self.logError)
     order_by = [
         Person.id, Person.datecreated, Person.name, Person.display_name
     ]
     limits = [1, datetime(2011, 7, 25, 0, 0, 0), 'foo', 'bar']
     result = range_factory.limitsGroupedByOrderDirection(order_by, limits)
     self.assertEqual([(order_by, limits)], result)
     order_by = [
         Desc(Person.id),
         Desc(Person.datecreated),
         Desc(Person.name),
         Desc(Person.display_name)
     ]
     result = range_factory.limitsGroupedByOrderDirection(order_by, limits)
     self.assertEqual([(order_by, limits)], result)
     order_by = [
         Person.id, Person.datecreated,
         Desc(Person.name),
         Desc(Person.display_name)
     ]
     result = range_factory.limitsGroupedByOrderDirection(order_by, limits)
     self.assertEqual([(order_by[:2], limits[:2]),
                       (order_by[2:], limits[2:])], result)
コード例 #4
0
    def preloadDataForBMPs(branch_merge_proposals, user):
        # Utility to load the data related to a list of bmps.
        # Circular imports.
        from lp.code.model.branch import Branch
        from lp.code.model.branchcollection import GenericBranchCollection
        from lp.registry.model.product import Product
        from lp.registry.model.distroseries import DistroSeries

        ids = set()
        source_branch_ids = set()
        person_ids = set()
        for mp in branch_merge_proposals:
            ids.add(mp.id)
            source_branch_ids.add(mp.source_branchID)
            person_ids.add(mp.registrantID)
            person_ids.add(mp.merge_reporterID)

        branches = load_related(
            Branch, branch_merge_proposals,
            ("target_branchID", "prerequisite_branchID", "source_branchID"))
        # The stacked on branches are used to check branch visibility.
        GenericBranchCollection.preloadVisibleStackedOnBranches(branches, user)

        if len(branches) == 0:
            return

        # Pre-load PreviewDiffs and Diffs.
        preview_diffs = IStore(BranchMergeProposal).find(
            PreviewDiff,
            PreviewDiff.branch_merge_proposal_id.is_in(ids)).order_by(
                PreviewDiff.branch_merge_proposal_id,
                Desc(PreviewDiff.date_created)).config(
                    distinct=[PreviewDiff.branch_merge_proposal_id])
        load_related(Diff, preview_diffs, ['diff_id'])
        for previewdiff in preview_diffs:
            cache = get_property_cache(previewdiff.branch_merge_proposal)
            cache.preview_diff = previewdiff

        # Add source branch owners' to the list of pre-loaded persons.
        person_ids.update(branch.ownerID for branch in branches
                          if branch.id in source_branch_ids)

        # Pre-load Person and ValidPersonCache.
        list(
            getUtility(IPersonSet).getPrecachedPersonsFromIDs(
                person_ids, need_validity=True))

        # Pre-load branches' data.
        load_related(SourcePackageName, branches, ['sourcepackagenameID'])
        load_related(DistroSeries, branches, ['distroseriesID'])
        load_related(Product, branches, ['productID'])
        GenericBranchCollection.preloadDataForBranches(branches)
コード例 #5
0
def extractTrendingHashtags(store, limit=10, duration=None):
    """Extract information about trending hashtags and store it in FluidDB.

    @param store: The storm store to query and to save our result to.
    @param limit: Optionally, the number of objects to retrieve.
    @param duration: Optionally, the recent time period to look at when
        determining which hashtags are trending.  Default is 28 days.

    The storm query below results in SQL like:

        SELECT COUNT(DISTINCT comments.object_id) AS count,
               about_tag_values.value,
               array_agg(ROW(comments.username, comments.creation_time))
        FROM about_tag_values, comment_object_link, comments
        WHERE about_tag_values.value LIKE '#%' AND
              about_tag_values.object_id = comment_object_link.object_id AND
              comments.object_id = comment_object_link.comment_id AND
              comments.creation_time >= '2012-11-09 07:42:40'::TIMESTAMP AND
              CHAR_LENGTH(about_tag_values.value) >= 2
        GROUP BY about_tag_values.value
        ORDER BY count DESC
        LIMIT 10
    """
    duration = timedelta(days=28) if duration is None else duration
    startTime = datetime.utcnow() - duration
    count = Alias(Count(Comment.objectID, distinct=True))
    result = store.find(
        (count, AboutTagValue.value,
         Func('array_agg', Row(Comment.username, Comment.creationTime))),
        Like(AboutTagValue.value,
             u'#%'), AboutTagValue.objectID == CommentObjectLink.objectID,
        Comment.objectID == CommentObjectLink.commentID,
        Comment.creationTime >= startTime,
        Func('CHAR_LENGTH', AboutTagValue.value) >= 2)
    result.group_by(AboutTagValue.value)
    result.order_by(Desc(count))
    result.config(limit=limit)

    data = [{
        'count': count,
        'usernames': _sortUsernames(usernames),
        'value': hashtag
    } for count, hashtag, usernames in result]

    user = getUser(u'fluidinfo.com')
    tagValues = TagValueAPI(user)
    objectID = ObjectAPI(user).create(u'fluidinfo.com')
    tagValues.set(
        {objectID: {
            u'fluidinfo.com/trending-hashtags': json.dumps(data)
        }})
    store.commit()
コード例 #6
0
 def __set__(self, obj, value):
     if obj._self_in_database is None:
         spph = Store.of(obj.distribution).find(
             SourcePackagePublishingHistory,
             SourcePackagePublishingHistory.distroseriesID ==
             DistroSeries.id,
             DistroSeries.distributionID == obj.distribution.id,
             SourcePackagePublishingHistory.sourcepackagenameID ==
             obj.sourcepackagename.id).order_by(
                 Desc(SourcePackagePublishingHistory.id)).first()
         obj._new(obj.distribution, obj.sourcepackagename,
                  is_upstream_link_allowed(spph))
     setattr(obj._self_in_database, self.attrname, value)
コード例 #7
0
 def source_mirror_freshness(self):
     """See IDistributionMirror"""
     store = Store.of(self)
     mirror = store.find(
         MirrorDistroSeriesSource,
         And(MirrorDistroSeriesSource.distribution_mirror == self,
             MirrorDistroSeriesSource.freshness !=
             MirrorFreshness.UNKNOWN)).order_by(
                 Desc(MirrorDistroSeriesSource.freshness)).first()
     if not mirror:
         return None
     else:
         return mirror.freshness
コード例 #8
0
    def test_lifecycle(self):
        """Test with an option that's part of the default sort.

        Sorting on LIFECYCYLE moves the lifecycle reference to the
        first element of the output."""
        # Check that this isn't a no-op.
        lifecycle_order = BranchListingView._listingSortToOrderBy(
            BranchListingSort.LIFECYCLE)
        self.assertSortsEqual([
            Desc(Branch.lifecycle_status),
            Asc(Product.name),
            Asc(Owner.name),
            Asc(Branch.name)
        ], lifecycle_order)
コード例 #9
0
    def _getBySubscriber(self, subscriber, archive, current_only,
                         with_active_tokens):
        """Return all the subscriptions for a person.

        :param subscriber: An `IPerson` for whom to return all
            `ArchiveSubscriber` records.
        :param archive: An optional `IArchive` which restricts
            the results to that particular archive.
        :param current_only: Whether the result should only include current
            subscriptions (which is the default).
        :param with_active_tokens: Indicates whether the tokens for the given
            subscribers subscriptions should be included in the resultset.
            By default the tokens are not included in the resultset.
        """
        # Grab the extra Storm expressions, for this query,
        # depending on the params:
        extra_exprs = self._getExprsForSubscriptionQueries(
            archive, current_only)
        origin = [
            ArchiveSubscriber,
            Join(TeamParticipation,
                 TeamParticipation.teamID == ArchiveSubscriber.subscriber_id)
        ]

        if with_active_tokens:
            result_row = (ArchiveSubscriber, ArchiveAuthToken)
            # We need a left join with ArchiveSubscriber as
            # the origin:
            origin.append(
                LeftJoin(
                    ArchiveAuthToken,
                    And(
                        ArchiveAuthToken.archive_id ==
                        ArchiveSubscriber.archive_id,
                        ArchiveAuthToken.person_id == subscriber.id,
                        ArchiveAuthToken.date_deactivated == None)))
        else:
            result_row = ArchiveSubscriber

        # Set the main expression to find all the subscriptions for
        # which the subscriber is a direct subscriber OR is a member
        # of a subscribed team.
        # Note: the subscription to the owner itself will also be
        # part of the join as there is a TeamParticipation entry
        # showing that each person is a member of the "team" that
        # consists of themselves.
        store = Store.of(subscriber)
        return store.using(*origin).find(
            result_row, TeamParticipation.personID == subscriber.id,
            *extra_exprs).order_by(Desc(ArchiveSubscriber.date_created))
コード例 #10
0
 def _parse_orderBy(cls, orderBy):
     result = []
     if not isinstance(orderBy, (tuple, list)):
         orderBy = (orderBy, )
     for item in orderBy:
         if isinstance(item, basestring):
             desc = item.startswith("-")
             if desc:
                 item = item[1:]
             item = cls._attr_to_prop.get(item, item)
             if desc:
                 item = Desc(item)
         result.append(item)
     return tuple(result)
コード例 #11
0
    def getReleasesAndPublishingHistory(self):
        """See `IDistributionSourcePackage`."""
        store = Store.of(self.distribution)
        result = store.find(
            (SourcePackageRelease, SourcePackagePublishingHistory),
            SourcePackagePublishingHistory.distroseries == DistroSeries.id,
            DistroSeries.distribution == self.distribution,
            SourcePackagePublishingHistory.archiveID.is_in(
                self.distribution.all_distro_archive_ids),
            SourcePackagePublishingHistory.sourcepackagename ==
            self.sourcepackagename, SourcePackageRelease.id ==
            SourcePackagePublishingHistory.sourcepackagereleaseID)
        result.order_by(Desc(SourcePackageRelease.id),
                        Desc(SourcePackagePublishingHistory.datecreated),
                        Desc(SourcePackagePublishingHistory.id))

        # Collate the publishing history by SourcePackageRelease.
        dspr_pubs = []
        for spr, pubs in itertools.groupby(result, operator.itemgetter(0)):
            dspr_pubs.append((DistributionSourcePackageRelease(
                distribution=self.distribution,
                sourcepackagerelease=spr), [spph for (spr, spph) in pubs]))
        return dspr_pubs
コード例 #12
0
    def _update_sintegra_data(self):
        data = self._driver.get_sintegra()
        if data is None:
            return

        store = new_store()
        # coupon_start and coupon_end are actually, start coo, and current coo.
        coupon_start = data.coupon_start
        coupon_end = data.coupon_end
        # 0 means that the start coo isn't known, fetch
        # the current coo from the the database and add 1
        # TODO: try to avoid this hack
        if coupon_start == 0:
            results = store.find(FiscalDayHistory,
                                 station=self._printer.station).order_by(
                                     Desc(FiscalDayHistory.emission_date))
            if results.count():
                coupon_start = results[0].coupon_end + 1
            else:
                coupon_start = 1

        # Something went wrong or no coupons opened during the day
        if coupon_end <= coupon_start:
            store.commit(close=True)
            return

        station = store.fetch(self._printer.station)
        day = FiscalDayHistory(
            store=store,
            emission_date=data.opening_date,
            station=station,
            serial=unicode(data.serial),
            # 1 -> 001, FIXME: should fix stoqdrivers
            serial_id=int(data.serial_id),
            coupon_start=coupon_start,
            coupon_end=coupon_end,
            crz=data.crz,
            cro=data.cro,
            reduction_date=TransactionTimestamp(),
            period_total=data.period_total,
            total=data.total)

        for code, value, type in data.taxes:
            FiscalDayTax(fiscal_day_history=day,
                         code=unicode(code),
                         value=value,
                         type=unicode(type),
                         store=store)
        store.commit(close=True)
コード例 #13
0
    def findRelatedArchives(self,
                            exclude_archive=None,
                            archive_purpose=ArchivePurpose.PPA,
                            required_karma=0):
        """See `IDistributionSourcePackage`."""

        extra_args = []

        # Exclude the specified archive where appropriate
        if exclude_archive is not None:
            extra_args.append(Archive.id != exclude_archive.id)

        # Filter by archive purpose where appropriate
        if archive_purpose is not None:
            extra_args.append(Archive.purpose == archive_purpose)

        # Include only those archives containing the source package released
        # by a person with karma for this source package greater than that
        # specified.
        if required_karma > 0:
            extra_args.append(KarmaTotalCache.karma_total >= required_karma)

        store = Store.of(self.distribution)
        results = store.find(
            Archive,
            Archive.distribution == self.distribution,
            Archive._enabled == True,
            Archive._private == False,
            SourcePackagePublishingHistory.archive == Archive.id,
            (SourcePackagePublishingHistory.status
             == PackagePublishingStatus.PUBLISHED),
            (SourcePackagePublishingHistory.sourcepackagerelease
             == SourcePackageRelease.id),
            (SourcePackagePublishingHistory.sourcepackagename
             == self.sourcepackagename),
            # Ensure that the package was not copied.
            SourcePackageRelease.upload_archive == Archive.id,
            # Next, the joins for the ordering by soyuz karma of the
            # SPR creator.
            KarmaTotalCache.person == SourcePackageRelease.creatorID,
            *extra_args)

        # Note: If and when we later have a field on IArchive to order by,
        # such as IArchive.rank, we will then be able to return distinct
        # results. As it is, we cannot return distinct results while ordering
        # by a non-selected column.
        results.order_by(Desc(KarmaTotalCache.karma_total), Archive.id)

        return results
コード例 #14
0
    def get_previous_build(self, tree, host, compiler, revision):
        from buildfarm.sqldb import Cast
        cur_build = self.get_build(tree, host, compiler, revision)

        result = self.store.find(StormBuild,
            Cast(StormBuild.tree, "TEXT") == Cast(tree, "TEXT"),
            Cast(StormBuild.host, "TEXT") == Cast(host, "TEXT"),
            Cast(StormBuild.compiler, "TEXT") == Cast(compiler, "TEXT"),
            Cast(StormBuild.revision, "TEXT") != Cast(revision, "TEXT"),
            StormBuild.id < cur_build.id)
        result = result.order_by(Desc(StormBuild.id))
        prev_build = result.first()
        if prev_build is None:
            raise NoSuchBuildError(tree, host, compiler, revision)
        return prev_build
コード例 #15
0
ファイル: runner.py プロジェクト: veloutin/tilde
    def listSharesToUpdate(self, since=None):
        zs = getUtility(IZStorm).get("tilde")
        zs.rollback()
        for home, status in itertools.groupby(
                zs.using(Home, LeftJoin(
                    HomeState,
                    Home.id == HomeState.id,
                )).find((Home, HomeState)).order_by(Home.id,
                                                    Desc(HomeState.ts)),
                operator.itemgetter(0)):

            status = [s.copy() for h, s in status if s is not None]
            if ((len(status) > 1) or (home.active and not status)
                    or (status and not home.match(status[0]))):
                yield home.copy(), status
コード例 #16
0
 def get_build(self, tree, host, compiler, revision=None, checksum=None):
     from buildfarm.sqldb import Cast
     expr = [
         Cast(StormBuild.tree, "TEXT") == Cast(tree, "TEXT"),
         Cast(StormBuild.host, "TEXT") == Cast(host, "TEXT"),
         Cast(StormBuild.compiler, "TEXT") == Cast(compiler, "TEXT"),
         ]
     if revision is not None:
         expr.append(Cast(StormBuild.revision, "TEXT") == Cast(revision, "TEXT"))
     if checksum is not None:
         expr.append(Cast(StormBuild.checksum, "TEXT") == Cast(checksum, "TEXT"))
     result = self.store.find(StormBuild, *expr).order_by(Desc(StormBuild.upload_time))
     ret = result.first()
     if ret is None:
         raise NoSuchBuildError(tree, host, compiler, revision)
     return ret
コード例 #17
0
    def get_a_fucking_random_submission(self, store):

        aits = store.find(InternalTip)
        self.failIfEqual(
            aits.count(), 0,
            "in our Eternal Mangekyō Sharingan, no InternalTip are available")

        rits = store.find(ReceiverTip)
        self.failIfEqual(
            rits.count(), 0,
            "in our Eternal Mangekyō Sharingan, no ReceiverTip are available")

        # just because
        # storm.exceptions.UnorderedError: Can't use first() on unordered result set
        rits.order_by(Desc(ReceiverTip.id))
        return serialize_receivertip(rits.first())
コード例 #18
0
def test_sale_with_delivery(mock_can_emit_nfe, client, sale_payload_new_client,
                            example_creator, store):
    sale_payload_new_client['delivery'] = {
        'freight_type': 'cif',
        'price': 15,
        'transporter': {
            'cnpj': '23335270000159',
            'name': 'Stoq Tecnologia',
            'address': {
                'street': 'Rua Rui Barbosa',
                'streetnumber': 2000,
                'district': 'Centro',
                'postal_code': '13560-120',
                'is_main_address': True,
                'city_location': {
                    'country': 'Brazil',
                    'state': 'SP',
                    'city': 'São Carlos',
                },
            }
        },
        'volumes': {
            'kind': 'Caixas',
            'quantity': 1,
            'net_weight': 2,
            'gross_weight': 3,
        }
    }

    response = client.post('/sale', json=sale_payload_new_client)
    sale = store.find(Sale).order_by(Desc(Sale.open_date)).first()

    assert response.status_code == 201
    assert sale.get_total_sale_amount() == 25
    assert len(list(sale.deliveries)) == 1
    delivery = list(sale.deliveries)[0]

    assert delivery.transporter == sale.transporter
    assert delivery.transporter.person.company.cnpj == '23.335.270/0001-59'
    assert delivery.transporter.person.name == 'Stoq Tecnologia'
    assert delivery.transporter.person.address.street == 'Rua Rui Barbosa'
    assert delivery.freight_type == 'cif'
    assert delivery.address.street == 'Rua Aquidaban'
    assert delivery.volumes_kind == 'Caixas'
    assert delivery.volumes_quantity == 1
    assert delivery.volumes_net_weight == 2
    assert delivery.volumes_gross_weight == 3
コード例 #19
0
def get_group_info(gid):
    """Get infos about the specified group.

    Includes:
    - participants in the group (ID, nickname & stats)
    - current DJ (ID & nickname)
    - info about last track
    """
    group = g.store.get(Group, gid)
    if group is None:
        raise helpers.BadRequest(errors.INVALID_GROUP, "group does not exist")
    userdict = dict()
    for user in group.users:
        userdict[user.id] = {'nickname': user.nickname}
    # Search for the last track that was played.
    results = g.store.find(GroupEvent, (GroupEvent.event_type == events.PLAY)
                           & (GroupEvent.group == group))
    track = None
    play_event = results.order_by(Desc(GroupEvent.created)).first()
    if play_event is not None:
        artist = play_event.payload.get('artist')
        title = play_event.payload.get('title')
        row = g.store.find(Track, (Track.artist == artist)
                           & (Track.title == title)).one()
        image = row.image if row is not None else None
        track = {
            'artist': artist,
            'title': title,
            'image': image,
        }
        for entry in play_event.payload.get('stats', []):
            if entry.get('uid') in userdict:
                uid = entry['uid']
                userdict[uid]['score'] = entry.get('score')
                userdict[uid]['predicted'] = entry.get('predicted', True)
    users = list()
    for key, val in userdict.iteritems():
        users.append({
            'uid': key,
            'nickname': val.get('nickname'),
            'score': val.get('score'),
            'predicted': val.get('predicted', True)
        })
    master = None
    if group.master is not None:
        master = {'uid': group.master.id, 'nickname': group.master.nickname}
    return jsonify(name=group.name, track=track, master=master, users=users)
コード例 #20
0
 def consecutive_failure_count(self):
     """See `ICodeImport`."""
     # This SQL translates as "how many code import results have there been
     # for this code import since the last successful one".
     # This is not very efficient for long lists of code imports.
     last_success = Func(
         "coalesce",
         Select(CodeImportResult.id,
                And(
                    CodeImportResult.status.is_in(
                        CodeImportResultStatus.successes),
                    CodeImportResult.code_import == self),
                order_by=Desc(CodeImportResult.id),
                limit=1), 0)
     return Store.of(self).find(CodeImportResult,
                                CodeImportResult.code_import == self,
                                CodeImportResult.id > last_success).count()
コード例 #21
0
ファイル: rtip.py プロジェクト: keichacon/GlobaLeaks
def get_messages_list(store, user_id, tip_id):

    rtip = access_tip(store, user_id, tip_id)

    msglist = store.find(Message, Message.receivertip_id == rtip.id)
    msglist.order_by(Desc(Message.creation_date))

    content_list = []
    for msg in msglist:
        content_list.append(receiver_serialize_message(msg))

        if not msg.visualized and msg.type == u'whistleblower':
            log.debug("Marking as readed message [%s] from %s" %
                      (msg.content, msg.author))
            msg.visualized = True

    return content_list
コード例 #22
0
def cleanup(interval, verbose):
    thresh = datetime.datetime.fromtimestamp(time.time() - interval * 60 * 60)
    store = uutils.get_store()
    for group in store.find(Group, Group.is_active == True):
        # Iterate over all active groups.
        last_event = store.find(GroupEvent,
                                GroupEvent.group == group).order_by(
                                    Desc(GroupEvent.created)).first()
        if (last_event is None and group.created < thresh
                or last_event is not None and last_event.created < thresh):
            # Group is old and has no event, or last event is old.
            if verbose:
                print "deactivating group %d (%s)" % (group.id, group.name)
            group.is_active = False
            for user in group.users:
                user.group = None
    store.commit()
コード例 #23
0
def get_anomaly_history(store, limit):
    anomalies = store.find(Anomalies).order_by(Desc(Anomalies.date))[:limit]

    anomaly_history = []
    for _, anomaly in enumerate(anomalies):
        anomaly_entry = dict({
            'date': datetime_to_ISO8601(anomaly.date),
            'alarm': anomaly.alarm,
            'events': [],
        })
        for event_name, event_amount in anomaly.events.iteritems():
            anomaly_entry['events'].append({
                'name': event_name,
                'amount': event_amount,
            })
        anomaly_history.append(anomaly_entry)

    return anomaly_history
コード例 #24
0
    def getRecentRevisionsForProduct(product, days):
        """See `IRevisionSet`."""
        # Here to stop circular imports.
        from lp.code.model.branch import Branch
        from lp.code.model.branchrevision import BranchRevision

        revision_subselect = Select(Min(Revision.id),
                                    revision_time_limit(days))
        # Only look in active branches.
        result_set = Store.of(product).find(
            (Revision, RevisionAuthor),
            Revision.revision_author == RevisionAuthor.id,
            revision_time_limit(days), BranchRevision.revision == Revision.id,
            BranchRevision.branch == Branch.id, Branch.product == product,
            Branch.lifecycle_status.is_in(DEFAULT_BRANCH_STATUS_IN_LISTING),
            BranchRevision.revision_id >= revision_subselect)
        result_set.config(distinct=True)
        return result_set.order_by(Desc(Revision.revision_date))
コード例 #25
0
    def test_whereExpressions__two_sort_columns_asc_desc(self):
        """If the ascending sort column c1, the descending sort column
        c2 and the memo values m1, m2 are specified, whereExpressions()
        returns two expressions where  the first expression is

            c1 == m1 AND c2 < m2

        and the second expression is

            c1 > m1
        """
        resultset = self.makeStormResultSet()
        range_factory = StormRangeFactory(resultset, self.logError)
        [where_clause_1, where_clause_2] = range_factory.whereExpressions(
            [Person.id, Desc(Person.name)], [1, 'foo'])
        self.assertEqual("Person.id = ? AND ((Person.name) < (E'foo'))",
                         compile(where_clause_1))
        self.assertEqual('(Person.id) > (1)', compile(where_clause_2))
コード例 #26
0
 def getUnlandedSourceBranchRevisions(self):
     """See `IBranchMergeProposal`."""
     store = Store.of(self)
     source = SQL("""source AS (SELECT BranchRevision.branch,
         BranchRevision.revision, Branchrevision.sequence FROM
         BranchRevision WHERE BranchRevision.branch = %s and
         BranchRevision.sequence IS NOT NULL ORDER BY BranchRevision.branch
         DESC, BranchRevision.sequence DESC
         LIMIT 10)""" % self.source_branch.id)
     where = SQL("""BranchRevision.revision NOT IN (SELECT revision from
         BranchRevision AS target where target.branch = %s and
         BranchRevision.revision = target.revision)""" %
                 self.target_branch.id)
     using = SQL("""source as BranchRevision""")
     revisions = store.with_(source).using(using).find(
         BranchRevision, where)
     return list(
         revisions.order_by(Desc(BranchRevision.sequence)).config(limit=10))
コード例 #27
0
ファイル: imageslave.py プロジェクト: 5l1v3r1/stoq-1
    def _refresh_slaves(self):
        empty_slave = self._slaves.pop(None, None)
        # If an image was set in the empty slave, promote it
        if empty_slave is not None and empty_slave.image_model is not None:
            self._slaves[empty_slave.image_model] = empty_slave
            empty_slave = None

        # If there is no empty slave, or the old one was promoted,
        # create a new one
        if empty_slave is None:
            empty_slave = ImageSlave(self.store,
                                     None,
                                     self.model,
                                     visual_mode=self.visual_mode)
            empty_slave.connect('image-changed',
                                self._on_image_slave__image_changed)

        # We need to reorganize the slaves because the order might have changed
        slaves = self._slaves.copy()
        self._slaves.clear()

        images = self.model.images.order_by(Desc(Image.is_main),
                                            Image.create_date)
        for image in images:
            slave = slaves.pop(image, None)
            if slave is None:
                slave = ImageSlave(self.store,
                                   image,
                                   self.model,
                                   visual_mode=self.visual_mode)
                slave.connect('image-changed',
                              self._on_image_slave__image_changed)

            slave.update_view()
            self._slaves[image] = slave

        # The empty slave is the last one
        self._slaves[None] = empty_slave

        # Remove slaves of removed images
        for removed in slaves.values():
            removed.disconnect_by_func(self._on_image_slave__image_changed)

        self._organize(force=True)
コード例 #28
0
    def get_FormValues(self, getall=True):
        id_form = int(self.context.forms_id)
        form = self.request.form

        if 'data_inicial' in form.keys():
            data_inicial = self.str2datetime(
                form.get('data_inicial')) + timedelta(days=0)
        else:
            data_inicial = self.str2datetime(self.get_data_inicial())

        if 'data_final' in form.keys():
            data_final = self.str2datetime(
                form.get('data_final')) - timedelta(days=-1)
        else:
            data_final = self.str2datetime(self.get_data_final())

        self.data_instance = ModelsFormInstance().store.find(
            ModelsFormInstance,
            ModelsFormInstance.forms_id == id_form,
            ModelsFormInstance.date_creation >= data_inicial,
            ModelsFormInstance.date_creation <= data_final,
        ).order_by(Desc(ModelsFormInstance.date_creation))

        self.ids_instances = [int(i.instance_id) for i in self.data_instance]

        L_value = []
        self.data_values = ModelsFormValues().store.find(
            ModelsFormValues, ModelsFormValues.forms_id == id_form,
            ModelsFormValues.date_creation >= data_inicial,
            ModelsFormValues.date_creation <= data_final,
            ModelsFormValues.instance_id.is_in(self.ids_instances))

        for item in self.data_instance:
            data = self.data_values.find(
                ModelsFormValues.instance_id == int(item.instance_id))
            if data.count() > 0:
                L_value.append(data)

        L = []
        for item in L_value:
            if self.checkItem(item, form):
                L.append(item)
        return L
コード例 #29
0
def test_sale_with_package_surcharge_in_price(mock_can_emit_nfe, client,
                                              sale_payload, example_creator,
                                              store):
    child1 = example_creator.create_product(price=88,
                                            description='child1',
                                            stock=5,
                                            code='98')
    child2 = example_creator.create_product(price=8,
                                            description='child2',
                                            stock=5,
                                            code='99')

    # But in a package, they have special prices
    package = example_creator.create_product(price=20,
                                             description=u'package',
                                             is_package=True)
    example_creator.create_product_component(product=package,
                                             component=child1,
                                             price=10)
    example_creator.create_product_component(product=package,
                                             component=child2,
                                             price=5,
                                             component_quantity=2)

    sale_payload['products'] = [{
        'id': package.id,
        'price':
        '25',  # the regular price is 20, but we are selling at a surcharge
        'quantity': 1,
    }]

    response = client.post('/sale', json=sale_payload)
    sale = store.find(Sale).order_by(Desc(Sale.open_date)).first()

    assert response.status_code == 201
    assert sale.get_total_sale_amount() == 25

    items = list(sale.get_items())
    item1 = list(filter(lambda i: i.sellable == child1.sellable, items))[0]
    item2 = list(filter(lambda i: i.sellable == child2.sellable, items))[0]
    assert item1.price == Decimal('12.50')
    assert item2.price == Decimal('6.25')
    assert item2.quantity == 2
コード例 #30
0
ファイル: karma.py プロジェクト: pombreda/UnnaturalCodeFork
    def getTopContributors(self, category=None, limit=None):
        """See IKarmaContext."""
        from lp.registry.model.person import Person
        store = IStore(Person)
        if IProduct.providedBy(self):
            condition = KarmaCache.productID == self.id
        elif IDistribution.providedBy(self):
            condition = KarmaCache.distributionID == self.id
        elif IProjectGroup.providedBy(self):
            condition = KarmaCache.projectID == self.id
        else:
            raise AssertionError("Not a product, project or distribution: %r" %
                                 self)

        if category is not None:
            category = category.id
        contributors = store.find(
            (Person, KarmaCache.karmavalue), KarmaCache.personID == Person.id,
            KarmaCache.categoryID == category, condition).order_by(
                Desc(KarmaCache.karmavalue)).config(limit=limit)
        return list(contributors)