Esempio n. 1
0
def get_labels_by_sender():
    if g.authorization is None:
        return create_message_response("Unauthorized", 401)
    username = g.authorization.get('sub')
    keys = db.keys(pattern='label*')
    data = []
    label_json = {}
    for key in keys:
        sender = db.hget(key, "sender").decode()
        if username == sender or g.authorization.get('role') == 'courier':
            label_id = key.decode().split(":")[1]
            link = Link('self', '/labels/' + label_id)
            addressee = db.hget(key, "addressee").decode()
            size = db.hget(key, "size").decode()
            po_box_id = db.hget(key, "POBoxId").decode()
            sent = db.hget(key, "sent").decode()
            label_json = {
                "id": label_id,
                "sender": sender,
                "addressee": addressee,
                "size": size,
                "poBox": po_box_id,
                "sent": sent,
            }
            data.append(Embedded(data=label_json, links=[link]))

    links = [Link('self', '/labels/{id}', templated=True)]
    document = Document(embedded={'data': Embedded(data=data)}, links=links)
    return document.to_json()
Esempio n. 2
0
def dashboard():
    data = {}
    links = []
    labels = []
    errors = []

    login = g.authorization.get("usr")
    links.append(Link("find", "/labels/{id}", templated=True))
    links.append(Link("label:new", "/labels", type="POST"))

    if login is None:
        errors.append("Brak autoryzacji")
        document = Document(data={"errors": errors}, links=links)
        return document.to_json(), 401

    for key in db.scan_iter("label:*"):
        if db.hget(key, "sender").decode() == login:

            status = db.hget(f"package:{db.hget(key, 'id').decode()}",
                             "status")
            if status is None:
                status = "Utworzona"
            else:
                status = status.decode()
            label = {}
            label = {
                "id": db.hget(key, "id").decode(),
                "name": db.hget(key, "name").decode(),
                "delivery_id": db.hget(key, "delivery_id").decode(),
                "size": db.hget(key, "size").decode(),
                "status": status
            }

            labels.append(label)

    items = []
    for label in labels:
        item_links = []
        link_info = Link("info", "/labels/" + label["id"], type="GET")
        item_links.append(link_info)
        if label["status"] == "Utworzona":
            link_delete = Link("delete",
                               "/labels/" + label["id"],
                               type="DELETE")
            item_links.append(link_delete)
        items.append(Embedded(data=label, links=item_links))

    document = Document(embedded={'labels': Embedded(data=items)}, links=links)
    return document.to_json(), 200
Esempio n. 3
0
def package_create():
    if g.authorization is None or g.authorization.get('role') != 'courier':
        return create_message_response("Unauthorized", 401)

    label_id = request.json.get('labelId')
    if not db.hexists(f"label:{label_id}", "size"):
        return create_message_response("Label not Found", 404)

    if not db.hget(f"label:{label_id}", "sent").decode() == 'false':
        return create_message_response("Label already sent", 400)

    db.hset(f"label:{label_id}", "sent", 'true')

    package_id = str(uuid.uuid4())

    db.hset(f"package:{package_id}", "packageId", f"{package_id}")
    db.hset(f"package:{package_id}", "labelId", f"{label_id}")
    db.hset(f"package:{package_id}", "status", "IN_TRANSIT")

    data = {
        "packageId": package_id,
        "labelId": label_id,
        "status": "IN_TRANSIT"
    }

    links = [Link('self', '/packages/{id}', templated=True)]
    document = Document(embedded={'data': Embedded(data=data)}, links=links)
    return document.to_json()
Esempio n. 4
0
def add_to_dashboard():

    token = get_token()
    if(token == None):
        return "Blad autoryzacji", 401
    login = token["login"]
    
    result = check_origin(request.origin)
    if(not result):
        return "Brak dostepu", 403
    
    r = get_db()
    
    package_id = uuid.uuid4()
    receiver = request.json.get('receiver')
    post_id = request.json.get('postId')
    size = request.json.get('size')
    
    if(
       receiver == "" or 
       post_id == "" or
       size == ""
       ):
           return "Pola nie moga byc puste", 422
    
    try:
        r.hset((str)(package_id), "receiver", receiver)
        r.hset((str)(package_id), "post_id", post_id)
        r.hset((str)(package_id), "size", size)
        r.hset((str)(package_id), "status", "waiting")
        r.rpush(login, (str)(package_id))
    except ConnectionError:
        return "Blad serwera", 503
        
    
    links = link.Collection(
        link.Link("delete", "/sender/dashboard/" + (str)(package_id)),
        link.Link("update", "/sender/dashboard/" + (str)(package_id))
    )
    package_info = {
        "packageId": (str)(package_id),
        "receiver": receiver,
        "postId": post_id,
        "size": size,
        "status": "waiting"
    }
    headers = {
        "Access-Control-Allow-Origin": request.origin
    }
    return HALResponse(response=Document(
        embedded={"newPackage": Embedded(data=package_info, links=links)}).to_json(), 
        headers=headers, 
        content_type="application/hal+json")
Esempio n. 5
0
def test_should_append_embedded_document():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(
            embedded={
                'orders': Embedded(
                    embedded={'details': Embedded(
                        data={'details': {}}
                    )},
                    links=link.Collection(
                        link.Link('foo', 'www.foo.com'),
                        link.Link('boo', 'www.boo.com')
                    ),
                    data={'total': 30},
                )
            },
            data={'currentlyProcessing': 14}
        )
        expected = {
            '_links': {
                'self': {
                    'href': flask.request.path
                }
            },
            '_embedded': {
                'orders': {
                    '_links': {
                        'foo': {'href': 'www.foo.com'},
                        'boo': {'href': 'www.boo.com'}
                    },
                    '_embedded': {
                        'details': {'details': {}}
                    },
                    'total': 30,
                }
            },
            'currentlyProcessing': 14
        }
        assert expected == document.to_dict()
Esempio n. 6
0
def label_delete(label_uuid):
    if g.authorization is None:
        return create_message_response("Unauthorized", 401)
    username = g.authorization.get('sub')
    if not db.hexists(f"label:{label_uuid}", "size"):
        return create_message_response("Label not Found", 404)
    if not db.hget(f"label:{label_uuid}", "sender").decode() == username:
        return create_message_response("Label not found", 404)
    db.delete(f"label:{label_uuid}")
    link = [Link('all', '/labels')]

    document = Document(embedded={'data': Embedded(data={})}, links=link)
    return document.to_json()
Esempio n. 7
0
def packages_get():
    if request.method == 'OPTIONS':
        return allowed_methods(['GET', 'POST'])
    if g.authorization is None or g.authorization.get('role') != 'courier':
        return create_message_response("Unauthorized", 401)

    keys = db.keys(pattern='package*')
    data = []
    package_json = {}
    for key in keys:
        package_id = key.decode().split(":")[1]
        link = Link('self', '/packages/' + package_id)
        status = db.hget(key, "status").decode()
        label_id = db.hget(key, "labelId").decode()
        package_json = {
            "id": package_id,
            "status": status,
            "labelId": label_id
        }
        data.append(Embedded(data=package_json, links=[link]))

    links = [Link('self', '/packages/{id}', templated=True)]
    document = Document(embedded={'data': Embedded(data=data)}, links=links)
    return document.to_json()
Esempio n. 8
0
def test_data_in_embedded_can_be_array():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(
            embedded={
                'order': Embedded(
                    data=[
                        {
                            'total': 30.00,
                            'currency': 'USD',
                            'status': 'shipped'
                        }, {
                            'total': 20.00,
                            'currency': 'USD',
                            'status': 'processing'
                        }
                    ]
                )
            },
            data={
                'currentlyProcessing': 14
            }
        )
        expected = {
            'currentlyProcessing': 14,
            '_links': {'self': {'href': '/entity/231'}},
            '_embedded': {
                'order': [{
                    'total': 30.00,
                    'currency': 'USD',
                    'status': 'shipped'
                }, {
                    'total': 20.00,
                    'currency': 'USD',
                    'status': 'processing'
                }]
            }
        }
        assert expected == document.to_dict()
Esempio n. 9
0
def test_data_in_embedded_can_be_array_of_documents():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(
            embedded={
                'order': Embedded(
                    data=[
                        Embedded(
                            data={
                                'total': 30.00,
                                'currency': 'USD',
                                'status': 'shipped'
                            },
                            links=link.Collection(
                                link.Link('foo', 'www.foo30.com'),
                                link.Link('boo', 'www.boo30.com')
                            ),
                        ),
                        Embedded(
                            data={
                                'total': 20.00,
                                'currency': 'USD',
                                'status': 'processing'
                            },
                            links=link.Collection(
                                link.Link('foo', 'www.foo20.com'),
                                link.Link('boo', 'www.boo20.com')
                            ),
                        )
                    ]
                )
            },
            data={
                'currentlyProcessing': 14
            }
        )
        expected = {
            'currentlyProcessing': 14,
            '_links': {'self': {'href': '/entity/231'}},
            '_embedded': {
                'order': [
                    {
                        '_links': {
                            'foo': {'href': 'www.foo30.com'},
                            'boo': {'href': 'www.boo30.com'}
                        },
                        'total': 30.00,
                        'currency': 'USD',
                        'status': 'shipped'
                    },
                    {
                        '_links': {
                            'foo': {'href': 'www.foo20.com'},
                            'boo': {'href': 'www.boo20.com'}
                        },
                        'total': 20.00,
                        'currency': 'USD',
                        'status': 'processing'
                    }
                ]
            }
        }
        assert expected == document.to_dict()
Esempio n. 10
0
def show_dashboard():

    token = get_token()
    if(token == None):
        return "Blad autoryzacji", 401
    login = token["login"]
    
    result = check_origin(request.origin)
    if(not result):
        return "Brak dostepu", 403
    
    r = get_db()
    
    try:
        if(login != "courier"):
            packages_number = r.llen(login)
            packages = r.lrange(login, 0, packages_number - 1)
        else:
            packages = []
            keys = r.keys()
            for key in keys:
                if(r.type(key) == b"hash"):
                    packages.append(key)
    except ConnectionError:
        return "Blad serwera", 503
        
    decoded_packages = [p.decode() for p in packages]
    
    dashboard = {}
    i = 1
    try:
        for dp in decoded_packages:
            receiver = r.hget(dp, "receiver").decode()
            post_id = r.hget(dp, "post_id").decode()
            size = r.hget(dp, "size").decode()
            status = r.hget(dp, "status").decode()
            package_name = "package" + (str)(i)
            dashboard[package_name] = Embedded(
                data={
                    "packageId": dp,
                    "receiver": receiver,
                    "postId": post_id,
                    "size": size,
                    "status": status
                },
                links=link.Collection(
                    link.Link("delete", "/sender/dashboard/" + (str)(dp)),
                    link.Link("update", "/sender/dashboard/" + (str)(dp))
                )
            )
            i = i + 1
    except ConnectionError:
        return "Blad serwera", 503
          
    headers = {
        "Access-Control-Allow-Origin": request.origin
    }
    return HALResponse(response=Document(
        data={"name": "dashboard"}, 
        embedded=dashboard).to_json(), 
        headers=headers, 
        content_type="application/hal+json")
Esempio n. 11
0
 def to_embedded(v):
     return Embedded(
         links=Collection(Link('self', '/versions/{}'.format(v.version))))