def add_new_task():
    body = json.loads(request.data)
    title = body.get('title', None)
    description = body.get('description', None)

    due_date = body.get('due_date', None)
    if due_date is not None:
        due_date = datetime.strptime(due_date , '%Y-%m-%d').date()

    new_task = Tasks(title=title, description=description, due_date=due_date)

    db.add(new_task)

    # Add assignee relation
    assignee_key = body.get('assignee_key',None)
    assignee = db.query(People).by_key(assignee_key)
    if assignee_key is not None:
        db.add(task_graph.relation(new_task, Assignee_Relation(), assignee))

    # Add category relation
    category_key = body.get('category_key', None)
    category = db.query(Categories).by_key(category_key)

    if category is not None:
        db.add(task_graph.relation(relation_from=category, relation=Category_Relation(), relation_to=new_task))

    return jsonify({'result': new_task._dump()})
Beispiel #2
0
    def get(self):
        blocks = db.query(Block).all()
        if not len(blocks):
            self.generateFirst()
            blocks = db.query(Block).all()

        return jsonify(blocks[::-1])
def edit_task():
    body = json.loads(request.data)
    task_key = body.get('_key', None)
    task = db.query(Tasks).by_key(task_key)
    if task is None:
        return jsonify({'message':'task not found'})

    name = body.get('name',None)
    description = body.get('description', None)
    task.name = name
    task.description = description
    db.update(task)

    category_key = body.get('category_key', None)
    category = db.query(Categories).by_key(category_key)
    if category is not None:
        # find old category relation and delete it
        old_category_relation = db.query(Category_Relation).filter('_to==@_to',_to=task._id).first()
        db.delete(old_category_relation)

        # add new category relation
        db.add(task_graph.relation(relation_from=category, relation=Category_Relation(), relation_to=task))

    assignee_key = body.get('assignee_key', None)
    assignee = db.query(People).by_key(assignee_key)
    if assignee is not None:
        # find old assignee relation and delete it
        old_assignee_relation = db.query(Assignee_Relation).filter('_from==@_from',_from=task._id).first()
        db.delete(old_assignee_relation)

        # add new assignee relation
        db.add(task_graph.relation(relation_from=task, relation=Assignee_Relation(), relation_to=assignee))

    return jsonify({'result':task._dump()}), 200
Beispiel #4
0
def parse_invoices(entries, account):
    for entry in entries:
        i = entry['invoices']
        invoice = db.query(Document).filter_by(uid=i['id']).first()
        partner = db.query(Partner).filter_by(uid=i['client_id']).first()

        if invoice is None:
            invoice = Document(uid=i['id'],
                               account=account,
                               tags=[typetags['invoice']])
            db.add(invoice)
        else:
            u = list(set(invoice.tags).difference(set(tags.values())))
            if u: invoice.tags = u

        invoice.name = i['subject']
        invoice.value = i['amount']
        invoice.date = datetime.strptime(i['issued_at'], '%Y-%m-%d')
        invoice.updated_at = datetime.strptime(i['updated_at'],
                                               '%Y-%m-%dT%H:%M:%SZ')
        invoice.meta = json.dumps(i)
        invoice.partner = partner
        invoice.tags.append(tags[i['state']])

        if i['state'] == 'open' and datetime.strptime(
                i['due_at'], '%Y-%m-%d') < datetime.now():
            invoice.tags.append(tags['due'])
Beispiel #5
0
def add_new_product():
    body = json.loads(request.data)
    name = body.get('name', None)
    if name is None:
        return jsonify({'error': 'name cannot be null'})
    description = body.get('description', None)
    imageLocation = body.get('imageLocation', None)
    price = body.get('price', None)
    discount = body.get('discount', None)
    new_product = Products(name=name,
                           description=description,
                           imageLocation=imageLocation,
                           price=price,
                           discount=discount)
    db.add(new_product)

    #add relations
    shop_key = body.get('shop_key', None)
    if shop_key is not None:
        shop = db.query(Shops).by_key(shop_key)
        if shop is not None:
            db.add(product_graph.relation(new_product, Shop_Relation(), shop))
    category_key = body.get('category_key', None)
    if category_key is not None:
        category = db.query(Categories).by_key(category_key)
        if category is not None:
            db.add(
                product_graph.relation(relation_from=category,
                                       relation=Shop_Relation(),
                                       relation_to=new_product))

    return jsonify({'result': new_product._dump()})
Beispiel #6
0
    def get(self, accountId=None, tags=None):

        args = parser.parse_args()

        if accountId and args is None:
            return jsonify(
                db.query(Account).filter_by(id=accountId).first().documents)

        q = db.query(Document)

        # if args['tags']:
        #     tags = args['tags'].split(',')
        #     for tag in tags:
        #         q = q.filter(Document.tags.any(Tag.slug == tag))

        if args['tags']:
            tags = args['tags'].split(',')
            q = q.filter(Document.tags.any(Tag.slug.in_(tags)))

        if args['exclude']:
            tags = args['exclude'].split(',')
            for tag in tags:
                q = q.filter(~Document.tags.any(Tag.slug == tag))

        if accountId:
            q = q.filter(Document.account == db.query(Account).filter_by(
                id=accountId).first())

        return jsonify(q.order_by(Document.date).all())
Beispiel #7
0
    def post(self):
        args = parser.parse_args()
        profile = db.query(Profile).filter_by(id=args['profile_id']).first()
        miner = db.query(Profile).filter_by(id=args['miner_id']).first()
        previous = db.query(Block).order_by('-id').first()

        data = {
            "message": profile.message,
            "feedback": args["feedback"],
            "initiator": profile.email,
            "miner": miner.email,
            "reward": 30
        }

        nonce, hash, timestamp = Block.pow(data=json.dumps(data),
                                           previous_hash=previous.hash)

        block = Block(data=json.dumps(data),
                      hash=hash,
                      previous_hash=previous.hash,
                      nonce=nonce,
                      creation_date=timestamp)

        miner.thelmies += 30
        profile.thelmies -= 5

        # remove message from profile
        profile.message = ""

        db.add(block)
        db.commit()

        return jsonify(block)
Beispiel #8
0
    def parseTotals(self, accountId):

        account = db.query(Account).filter_by(id=accountId).first()
        turnover = 0
        expected = 0

        # Turn-over 12 months
        invoices = db.query(Document).filter(
            Document.date >= datetime.now() - relativedelta(years=1),
            Document.tags.any(Tag.slug.in_(['open', 'paid'])),
            Document.tags.any(Tag.slug == 'invoice'),
            Document.account == account).all()

        for document in invoices:
            meta = json.loads(document.meta)
            turnover += meta['amount'] - meta['tax_amount']

        # Expected
        invoices = db.query(Document).filter(
            Document.tags.any(Tag.slug.in_(['open', 'draft'])),
            Document.tags.any(Tag.slug == 'invoice'),
            Document.account == account).all()

        for document in invoices:
            meta = json.loads(document.meta)
            expected += meta['amount'] - meta['tax_amount']

        return turnover, expected
Beispiel #9
0
def edit_product():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})
    product = db.query(Products).by_key(key)
    if product is None:
        return jsonify({'error': 'product not found'})

    # TODO this but programmatically if things change
    name = body.get('name', None)
    if name is not None:
        product.name = name
    description = body.get('description', None)
    if description is not None:
        product.description = description
    imageLocation = body.get('imageLocation', None)
    if imageLocation is not None:
        product.imageLocation = imageLocation
    price = body.get('price', None)
    if price is not None:
        product.price = price
    discount = body.get('discount', None)
    if discount is not None:
        product.discount = discount
    db.update(product)

    #relations
    category_key = body.get('category_key', None)
    category = db.query(Categories).by_key(category_key)
    if category is not None:
        # find old category relation and delete it
        old_category_relation = db.query(Category_Relation).filter(
            '_to==@_to', _to=product._id).first()
        db.delete(old_category_relation)
        # add new category relation
        db.add(
            product_graph.relation(relation_from=category,
                                   relation=Category_Relation(),
                                   relation_to=product))
    shop_key = body.get('shop_key', None)
    shop = db.query(Shops).by_key(shop_key)
    if shop is not None:
        # find old assignee relation and delete it
        old_shop_relation = db.query(Shop_Relation).filter(
            '_from==@_from', _from=product._id).first()
        db.delete(old_shop_relation)
        # add new assignee relation
        db.add(
            product_graph.relation(relation_from=product,
                                   relation=Shop_Relation(),
                                   relation_to=shop))

    return jsonify({'result': product._dump()})
Beispiel #10
0
def harvestLastUpdated(accountId = None):
    query = db.query(Document).filter(
        Document.updated_at < datetime.now() - timedelta(seconds=15),
        Document.tags.any(Tag.slug == 'source'),
        Document.tags.any(Tag.slug == 'harvest'))

    if accountId is not None:
        query.filter(Document.account_id == accountId)

    sources = query.all()
    amount = 0

    for source in sources:
        meta = json.loads(source.meta)

        r = harvest.get_request(meta['url'] % '/invoices?updated_since=%s' % source.updated_at)
        invoices = r.json()

        if len(invoices) > 0:
            print('About to parse %s invoices' % len(invoices))

            amount += 1
            source.updated_at = datetime.now()
            harvest.parse_invoices(invoices, source.account)

    if amount > 0:
        db.commit()

    return amount
Beispiel #11
0
def googleLastUpdated(accountId = None):

    service = get_drive_service()

    query = db.query(Document).filter(
        Document.updated_at < datetime.now() - timedelta(seconds=15),
        Document.tags.any(Tag.slug == 'source'),
        Document.tags.any(Tag.slug == 'google_sheet'))

    if accountId is not None:
        query.filter(Document.account_id == accountId)

    sheets = query.all()
    amount = 0

    for sheet in sheets:
        results = service.files().get(fileId=sheet.uid, fields='name, modifiedTime').execute()

        if datetime.strptime(results['modifiedTime'], "%Y-%m-%dT%H:%M:%S.%fZ") > sheet.updated_at:
            print('This is what we fetched: %s.' % sheet.name)
            sheet.name = results['name']
            sheet.updated_at = datetime.now()
            google.parseGoogleSheet(sheet)
            amount+= 1

    ### Add Documents to DB
    if amount > 0:
        db.commit()

    return amount
Beispiel #12
0
def get_or_create(model, **kwargs):
    instance = db.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        return instance
Beispiel #13
0
def list_clients():
    clients = db.query(Clients).all()
    result = []
    for client in clients:
        result.append(client._dump())

    return jsonify({'result': result})
Beispiel #14
0
def edit_shop():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})
    shop = db.query(Shops).by_key(key)

    # TODO this but programmatically if things change
    name = body.get('name', None)
    if name is not None:
        shop.name = name
    slogan = body.get('slogan', None)
    if slogan is not None:
        shop.slogan = slogan
    description = body.get('description', None)
    if description is not None:
        shop.description = description
    logoLocation = body.get('logoLocation', None)
    if logoLocation is not None:
        shop.logoLocation = logoLocation
    geolocation = body.get('geolocation', None)
    if geolocation is not None:
        shop.geolocation = geolocation
    foundingDate = body.get('foundingDate', None)
    if foundingDate is not None:
        shop.foundingDate = foundingDate
    db.update(shop)

    return jsonify({'result': shop._dump()})
Beispiel #15
0
def list_categories():
    categories = db.query(Categories).all()
    result = []
    for category in categories:
        result.append(category._dump())

    return jsonify({'result': result})
Beispiel #16
0
def list_shops():
    shops = db.query(Shops).all()
    result = []
    for shop in shops:
        result.append(shop._dump())

    return jsonify({'result': result})
Beispiel #17
0
def edit_client():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})

    name = body.get('name', None)
    username = body.get('username', None)
    password = body.get('password', None)
    courriel = body.get('courriel', None)

    if name is None:
        return jsonify({'error': 'name cannot be null'})

    if username is None:
        return jsonify({'error': 'username cannot be null'})

    if password is None:
        return jsonify({'error': 'password cannot be null'})

    if courriel is None:
        return jsonify({'error': 'courriel cannot be null'})

    client = db.query(Clients).by_key(key)
    client.name = name
    client.username = username
    client.password = password
    client.courriel = courriel

    db.update(client)

    return jsonify({'result': client._dump()})
Beispiel #18
0
def parse_document(record, account, typestring):
    document = db.query(Document).filter_by(uid=record['uid']).first()
    partner = get_or_create(Partner, name=record['meta']['client_name'])

    if document is None:
        document = Document(**record)
        document.account = account
        document.tags = [typetags[typestring]]
        db.add(document)
    else:
        u = list(set(document.tags).difference(set(tags.values())))
        if u: document.tags = u

        document.name = record['name']
        document.value = record['value']
        document.date = record['date']

    document.updated_at = datetime.now()
    document.meta = CustomJSONEncoder().encode(record['meta'])
    document.partner = partner
    document.tags.append(tags[record['meta']['state']])

    if record['meta'][
            'state'] == 'open' and record['meta']['due_at'] < datetime.now():
        document.tags.append(tags['due'])
def list_people():
    people = db.query(People).all()
    result = []
    for person in people:
        result.append(person._dump())

    return jsonify({'result':result})
Beispiel #20
0
    def put(self, id):
        args = parser.parse_args()
        profile = db.query(Profile).filter_by(id=id).first()

        profile.message = args['message']
        db.commit()

        return jsonify(profile)
Beispiel #21
0
def delete_shop():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})

    shop = db.query(Shops).by_key(key)
    db.delete(shop)
    return jsonify({'result': 'success'})
def delete_person():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})

    person = db.query(People).by_key(key)
    db.delete(person)
    return jsonify({'result': 'success'})
def remove_categories():
    body = json.loads(request.data)
    category_key = body.get('_key', None)
    category = db.query(Categories).by_key(category_key)
    if category is not None:
        db.delete(category)
    else:
        return jsonify({'error':'Category not found'}), 200
    return jsonify({'result': 'success'}), 200
Beispiel #24
0
def delete_clients():
    body = json.loads(request.data)
    key = body.get('_key', None)
    if key is None:
        return jsonify({'error': 'key cannot be null'})

    client = db.query(Clients).by_key(key)
    db.delete(client)
    return jsonify({'result': 'success'})
def remove_task():
    body = json.loads(request.data)
    task_key = body.get('_key', None)
    task = db.query(Tasks).by_key(task_key)
    if task is None:
        return jsonify({'message': 'task not found'})

    db.delete(task)
    return jsonify(({'message':'success'}))
Beispiel #26
0
    def get(self):
        args = parser.parse_args()
        password = hashlib.sha224(args['password'].encode('utf-8')).hexdigest()
        profile = db.query(Profile).filter_by(email=args['email']).filter_by(
            password=password).first()

        abort_none_exists(profile, Profile)

        return jsonify(profile)
Beispiel #27
0
def parse_partners(entries):
    for entry in entries:
        c = entry['client']
        partner = db.query(Partner).filter_by(uid=c['id']).first()
        if partner is None:
            partner = Partner(uid=c['id'])
            db.add(partner)

        partner.name = c['name']
        partner.meta = json.dumps(c)
def edit_categories():
    body = json.loads(request.data)
    category_name = body.get('name', None)
    category_key = body.get('_key',None)
    category = db.query(Categories).by_key(category_key)
    if category is not None:
        category.name = category_name
        db.update(category)
    else:
        return jsonify({'error':'Category not found'}), 200

    return jsonify({'result': category._dump()}), 200
Beispiel #29
0
def list_products():
    products = db.query(Products).all()
    result = []
    for product in products:
        product_dict = product._dump()
        product_graph.expand(product, depth=1, direction='any')
        shop_name = product._relations['shop_relation'][0]._object_to.name
        category_name = product._relations['category_relation'][
            0]._object_from.name
        product_dict['shop'] = shop_name
        product_dict['category'] = category_name
        result.append(product_dict)

    return jsonify({'result': result})
def list_tasks():
    tasks = db.query(Tasks).all()
    result = []
    for task in tasks:
        task_dict = task._dump()
        task_graph.expand(task, depth=1, direction='any')
        assignee_name = task._relations['assignee_relation'][0]._object_to.name
        category_name = task._relations['category_relation'][0]._object_from.name
        task_dict['assignee'] = assignee_name
        task_dict['category'] = category_name

        result.append(task_dict)

    return jsonify({'result': result})