예제 #1
0
 def newcontext(self, user=None):
     if user is None:
         user = self.user
     ctx = commit.CommitContext(self.database, user)
     ctx.setMayChange(True)
     ContextBroker().pushContext(ctx)
     return ctx
예제 #2
0
    def test_runAfterCommitFailing(self):
        py.test.xfail("post-commit hooks not supported")
        callbackCalled = []

        def callback(tid, *args, **kw):
            callbackCalled.append((tid, args, kw))
            raise RuntimeError('error')

        def callback2(tid, *args, **kw):
            callbackCalled.append((tid, args, kw))

        class Op(commit.OperateBase):
            def checkPermissions(self, context):
                pass

            def operate(self, context):
                context.runAfterCommit(callback, 42, foo='bar')
                context.runAfterCommit(callback2, 43)

        cctx = commit.CommitContext(self.database)
        ContextBroker().pushContext(cctx)
        cctx.setMayChange(True)

        results = cctx.runCommit([Op()])

        assert callbackCalled == [(None, (42, ), {
            'foo': 'bar'
        }), (None, (43, ), {})]
예제 #3
0
def main():
    database = accounting.db.connect()
    if (isinstance(database.connection, pymongo.MongoClient)
            and not pytransact.utils.is_localhost_primary(database.client)):
        sys.stderr.write('Run upgrade.py on the MongoDB primary.\n')
        raise SystemExit()

    ensure_indexes(database)
    cleanup_commits(database)
    pytransact.utils.update_bases(database, blm.accounting.User)
    pytransact.utils.update_bases(database, blm.members.PGPaymentFile)
    pytransact.utils.update_bases(database, blm.members.PGPayment)

    #cleanup_toirefs(database)

    interested = 'upgrade-%s' % ObjectId()
    with commit.CommitContext(database) as ctx:
        ops = [
            commit.CallBlm('accounting', 'bootstrap', []),
            commit.CallBlm('accounting', 'upgrade', []),
            commit.CallBlm('members', 'upgrade', [])
        ]
        ctx.runCommit(ops, interested=interested)
    result, error = commit.wait_for_commit(database, interested=interested)
    assert not error, error

    log.info('Done.')
예제 #4
0
    def test_SortedQuery_fulltext_update(self):
        py.test.skip('full text index disabled for now')
        from blm import testblm
        with commit.CommitContext(self.database, user=self.user) as ctx:
            ctx.setMayChange(True)
            oid1 = ObjectId()
            toi1 = ctx.createToi(blm.testblm.Test, oid1, {'name': ['foo']})
            ctx.runCommit([])

        self.sync()

        query = blm.testblm.Test._query(id=Query.Fulltext('bar'))

        link = Link.LinkSortedQuery(
            self.clientId, self.linkId, {
                'criteria': query,
                'attrList': ['name'],
                'subscription': True,
                'sorting': 'name'
            })
        link.run()
        self.sync()
        x = self._getResult()
        assert x['diffops'] == []
        toi1, = blm.testblm.Test._query(id=oid1).run()
        with commit.CommitContext(self.database) as ctx:
            ctx.setMayChange(True)
            ctx.changeToi(toi1, {'name': ['foo bar']})
            ctx.runCommit([])
        mongo.update_one(self.database.links, {
            'client': self.clientId,
            'link': self.linkId
        }, {'$set': {
            'outdatedBy': ObjectId(),
            'outdatedToids': [oid1]
        }})
        self.sync()

        link = Link.LinkFactory().create(None, self.clientId, self.linkId)
        link.run()
        self.sync()
        x = self._getResult()
        assert x['diffops'] == [[0, 0, [toi1]]]
예제 #5
0
def main(pipe):
    database = accounting.db.connect()

    with context.ReadonlyContext(database) as ctx:
        print 'Fetching accounts and balances.'
        accounts = [
            account for account in blm.accounting.Account._query(
                _attrList=['balance', 'balance_quantity']).run()
        ]
        balances = dict((toi.id[0], (toi.balance[0], toi.balance_quantity[0]))
                        for toi in accounts)
        accounts = [account.id[0] for account in accounts]

    for n, toids in enumerate(iterate.chunks(accounts, 100)):
        interested = 'update-%s' % toids[0]
        print 'Creating commit %d for %s' % (n, interested)
        with commit.CommitContext(database) as ctx:
            blm.accounting.Account._query(id=toids,
                                          _attrList=[
                                              'opening_balance',
                                              'opening_quantity', 'balance',
                                              'quantity'
                                          ]).run()
            ops = []
            for toid in toids:
                op = commit.CallToi(toid, 'updateBalance', [])
                ops.append(op)
            ctx.runCommit(ops, interested=interested)
        pipe.send(interested)
    pipe.send(None)
    pipe.close()

    with context.ReadonlyContext(database) as ctx:
        print 'Fetching accounts and balances for verification.'
        accounts = [
            account for account in blm.accounting.Account._query(
                _attrList=['balance', 'balance_quantity']).run()
        ]
        new_balances = dict(
            (toi.id[0], (toi.balance[0], toi.balance_quantity[0]))
            for toi in accounts)

    for account, old in balances.iteritems():
        new = new_balances.get(account)
        if new != old:
            print 'DIFF: %s %r -> %r' % (account, old, new)
예제 #6
0
def _invoke(request, database, user, op):
    interested = 'invoke-%s' % ObjectId()

    with commit.CommitContext(database, user) as ctx:
        cmt = ctx.runCommit([op], interested=interested)

    result, error = commit.wait_for_commit(database,
                                           interested,
                                           onfail=InternalServerError())

    if error:
        raise error

    if result[0]:
        result = result[0][0]

    resp = flask.jsonify(**result)
    return resp
예제 #7
0
    def test_commit_deleted(self):
        toi = blm.testcommit.Test()
        self.commit()

        ctx1 = commit.CommitContext(self.database)
        ctx1.setMayChange(True)
        with ctx1:
            toi1 = blm.testcommit.Test._query(id=toi.id).run()[0]
            op = commit.ChangeToi(toi1, {'name': ['bar']})

            interested = ObjectId()
            c = ctx1.runCommit([op],
                               interested=interested,
                               processCommits=False)

        toi._delete()
        self.commit()

        ctx1.processCommits(c)

        result, error = commit.wait_for_commit(self.database, interested)
        assert error
예제 #8
0
    b'#RTRANS': ('T* L N [D] [T] [N] [T]', Parser.added_transaction),
    b'#BTRANS': ('T* L N [D] [T] [N] [T]', Parser.deleted_transaction),
    b'#KSUMMA': ('[T]', Parser.no_op),

    # Non standard Open End extensions
    b'#AVSLUTAT': ('', Parser.closed),  # the accounting year is closed
    b'#SERIE': ('T [T]', Parser.series),
    b'#MOMSKOD': ('T T', Parser.vatcode),
}

if __name__ == '__main__':
    import bson, locale, sys
    locale.setlocale(locale.LC_CTYPE, '')
    enc = locale.getpreferredencoding()
    database = db.connect()
    for fname in sys.argv[1:]:
        fname = fname.decode(enc)
        sys.stdout.write('Importing %s ' % fname)
        sys.stdout.flush()
        interested = bson.objectid.ObjectId()
        with commit.CommitContext(database) as ctx:
            ctx.setMayChange(True)
            importer = SIEImporter()
            importer.parseFile(fname)
            accountingId = importer.accounting.id[0]
            ctx.runCommit([], interested=interested)
        result, errors = commit.wait_for_commit(database,
                                                interested=interested)
        assert not errors
        sys.stdout.write('done, created: %s\n' % accountingId)
예제 #9
0
 def test_simple(self):
     cctx = commit.CommitContext(self.database)
예제 #10
0
 def jslink():
     jslink = JsLink(linkFactory=link.LinkFactory())
     with commit.CommitContext(self.database):
         result = jslink.render(flask.request)
     return result