示例#1
0
def truckPut(id):
    truck_id = helper.get_one(Truck, truck_id=id)
    if truck_id is None:  # unacceptable parameter
        return "the <id> sent isn't related to any existing entry on the server\n", 400

    new_prov_id = request.form and request.form["provider_id"] or request.json and request.json.get("provider_id")

    if new_prov_id is None or not new_prov_id.isnumeric() or helper.get_one(Provider, id=int(new_prov_id)) is None:
        return 'invalid or non existing provider_id, please check provider_id sent in the request\n', 400

    truck_id.provider_id = new_prov_id
    helper.commit_changes()
    return 'OK\n', 200
示例#2
0
def put_collection(id):
    new_name = (request.form and request.form["name"]) or (request.json and request.json.get("name"))
    if new_name is None:
        return 'Bad parameters, expected {"name":"<name>"} or "name=<name>\n"', 400
    found_id = helper.get_one(Provider, id=id)
    if found_id is None:
        return "the <id> sent isn't related to any existing entry on the server\n", 406

    if helper.get_one(Provider, name=new_name):
        return "new Provider name already Exists\n", 400
    found_id.name = new_name
    helper.commit_changes()
    return "", 200
示例#3
0
def test1():
    # helper.add_instance(Provider, name="provider1")
    # helper.add_instance(Provider, name="provider2")
    # helper.add_instance(Rate, product_name="potatoes", rate=350, scope='ALL')
    # helper.add_instance(Rate, product_name="cucumbers", rate=290, scope='ALL')
    # provider1_id = helper.get_one(Provider, name="provider1").id
    # helper.add_instance(Rate, product_name="red_orange", rate=990, scope=provider1_id)
    # return str(provider1_id)

    # helper.add_instance(Truck, truck_id="123ABC",weight=250, provider_id=1)
    truck1 = helper.get_one(Truck, truck_id='123ABC')
    return str(truck1)
示例#4
0
    def test_put_nonexist_truck_id(self):
        tid = "foo"
        truck = helper.get_one(Truck, truck_id=tid)
        if truck is not None:
            db.session.remove(truck)
            helper.commit_changes()
        print("testing put request with truck_id not found in truck table ...")

        with self.app.test_client() as c:
            resp = c.put(f'/truck/{tid}')
            print("response: ", resp.data)
            self.assert_400(resp,
                            "Fail: put request with nonexistent truck param")
示例#5
0
def provider():
    try:
        name = json.loads(request.data)['name']

    except (TypeError, KeyError):
        return 'Bad parameters, expected {"name":"<name>"}\n', 400

    found_name = helper.get_one(Provider, name=name)

    if found_name:
        return "Provider already Exists\n", 400

    else:
        return create_id(name), 200
示例#6
0
def truckGet(id):
    if request.method == 'GET':
        truck = helper.get_one(Truck, truck_id=id)
        if truck is None:
            return ('truck ID not exist', 404)
        now = datetime.now()
        from_default = now.strftime('%Y%m') + '01000000'
        to_default = now.strftime('%Y%m%d%H%M%S')

        from_arg = request.args.get('from')
        if not from_arg:
            from_arg = from_default
        else:
            if len(from_arg) != 14:
                return "wrong datetime value"
            try:
                datetime(from_arg[0:4], from_arg[4:6], from_arg[6:8],
                         from_arg[8:10], from_arg[10:12], from_arg[12:14])
            except (ValueError):
                return "wrong datetime value"

        to_arg = request.args.get('to')
        if not to_arg:
            to_arg = to_default
        else:
            if len(to_arg) != 14:
                return "wrong datetime value"
            try:
                datetime(to_arg[0:4], to_arg[4:6], to_arg[6:8], to_arg[8:10],
                         to_arg[10:12], to_arg[12:14])
            except (ValueError):
                return "wrong datetime value"

    try:
        truck_info = get_truck_info(truck.truck_id, from_arg, to_arg).json()
        return jsonify(id=truck.truck_id,
                       tara=truck_info['tara'],
                       sessions=truck_info['sessions'])
    except JSONDecodeError as json_error:
        return jsonify(id=truck.truck_id,
                       tara=None,
                       sessions=f'Json responce decoding error: {json_error}')
示例#7
0
def truck():
    if request.method == 'POST':

        provider_id = (request.form and request.form["provider_id"]) or (
            request.json and request.json.get("provider_id"))
        truck_id = (request.form and request.form["truck_id"]) or (
            request.json and request.json.get("truck_id"))

        queried_provider = helper.get_one(Provider, id=provider_id)

        if queried_provider and truck_id:
            helper.add_instance(Truck,
                                truck_id=truck_id,
                                provider_id=queried_provider.id)
            return 'truck was added successfully'

        elif not queried_provider:
            return 'Provider was not found'

        elif not truck_id:
            return 'Please provide a valid truck ID'
示例#8
0
def upload_xml_data():
    data = (request.form
            and request.form["file"]) or (request.json
                                          and request.json.get("file"))

    if data is None or not os.path.isfile(XLSX_DIR + data):
        return 'Bad parameters, expected {"file":"<name>"} or "file=<name>"\n', 400
    xlsx_file = Path(XLSX_DIR + data)
    try:
        wb_obj = load_workbook(xlsx_file)
    except:
        return f'Bad file {data}, unreadable or wrong format\n', 500
    sheet = wb_obj.active

    title = True
    for row in sheet.iter_rows():
        if title:  # first row is title we skip it
            title = False
            continue

        record = helper.get_one(Rate,
                                product_name=row[0].value,
                                scope=row[2].value)
        if record is not None:
            # TODO: should we check the case were there is ALL scope after provider scope and keep only ALL scope ?
            record.rate = row[1].value
            helper.commit_changes()
        else:
            helper.add_instance(Rate,
                                product_name=row[0].value,
                                rate=row[1].value,
                                scope=row[2].value)

        TimeUtils.set_file_last_modified(XLSX_DIR + data, TimeUtils.get_now())

    return 'OK\n', 200
示例#9
0
def create_id(name):
    helper.add_instance(Provider, name=name)
    new_name = helper.get_one(Provider, name=name)
    return jsonify(id=new_name.id, name=new_name.name)
示例#10
0
def bill(id):
    provider = helper.get_one(Provider, id=id)
    if provider is None:
        return "wrong provider id", 400

    now = datetime.now()
    from_default = now.strftime('%Y%m') + '01000000'
    to_default = now.strftime('%Y%m%d%H%M%S')

    from_arg = request.args.get('from')
    if not from_arg:
        from_arg = from_default

    else:
        if len(from_arg) != 14:
            return "wrong datetime value"
        try:
            datetime(from_arg[0:4], from_arg[4:6], from_arg[6:8],
                     from_arg[8:10], from_arg[10:12], from_arg[12:14])
        except ValueError:
            return "wrong datetime value"

    to_arg = request.args.get('to')
    if not to_arg:
        to_arg = to_default
    else:
        if len(to_arg) != 14:
            return "wrong datetime value"
        try:
            datetime(to_arg[0:4], to_arg[4:6], to_arg[6:8], to_arg[8:10],
                     to_arg[10:12], to_arg[12:14])
        except ValueError:
            return "wrong datetime value"

    mocked_json = json.dumps({
        "id":
        'BAD RESPONSE FROM WEIGHT SERVER',
        "name":
        provider.name,
        "from":
        from_arg,
        "to":
        to_arg,
        "truckCount":
        0,
        "sessionCount":
        0,
        "products": [
            {
                "product": "orange",
                "count": 5,
                "amount": 500,
                "rate": 100,
                "pay": 50000
            },
            {
                "product": "mandarina",
                "count": 3,
                "amount": 300,
                "rate": 200,
                "pay": 60000
            },
        ],
        "total":
        110000
    })

    #1 - get list of truck_id references to provider.id
    #2 - for every truck, request get item (truck_id, from, to)
    #3 - count amount of non-empty json['sessions'] responces =>truckCount
    #4 - get sessions list from these responces: sessions = [ses1, ses2, ...]
    #5 - len(sessions) => sessionsCount
    #6 - for every session, count (with dict) products= {product_id1:(number of session with this product_id, total neto weight)}
    #7 - search for price, first check Rates(product_id, provider.id) for rate, if not found - only Rates(product_id) (All scope)
    #8 - pay = amount*rate
    #9 - total = sum(products['pay'])

    #1
    trucks = helper.get_all_with_filter(Truck, provider_id=provider.id)
    #2
    try:
        truckCounter = 0
        sessionCounter = 0
        sessions = []
        for truck in trucks:
            truck_id = truck.truck_id
            response = requests.get(WEIGHT_URI + f'/item/{truck_id}',
                                    params={
                                        'from': from_arg,
                                        'to': to_arg
                                    })
            response.raise_for_status()
            truck_sessions = response.json()['sessions']
            #3
            if len(truck_sessions) > 0:
                truckCounter += 1
    #5
            sessionCounter += len(truck_sessions)
            #4
            for session in truck_sessions:
                sessions.append(session)
        products = dict()
        #6
        for session in sessions:
            repsonse = requests.get(WEIGHT_URI + 'f/session/{session}')
            response.raise_for_status()
            session_data = response.json()
            product_id = session_data['product_id']
            #session counter, total neto weight, price (rate) and pay
            products.setdefault(product_id, [0, 0, 0, 0])
            products[product_id][0] += 1
            if session_data['neto'].isdigit():
                products[product_id][1] += session_data['neto']
    #7
        for product_name, product_data in products.items():
            price = helper.get_one(Rate,
                                   product_name=product_name,
                                   provider_id=provider.id)
            if price is None:
                price = helper.get_one(Rate, product_name=product_name)
            if price is None:
                #NOTIFY USER THAT PRICE OF product_id IS MISSING IN DB
                price = DEFAULT_PRICE
            product_data[2] = price
    #8, 9
        total = 0
        for product_name, product_data in products.items():
            pay = product_data[1] * product_data[2]
            product_data[3] = pay
            total += pay

        products_output = list()
        for product_name, product_data in products.items():
            products_output.append({
                "product": product_name,
                "count": product_data[0],  #number of sessions
                "amount": product_data[1],  #total kg
                "rate": product_data[2],  #agorot
                "pay": product_data[3]  #agorot
            })
        output_json = json.dumps({
            "id": provider.id,
            "name": provider.name,
            "from": from_arg,
            "to": to_arg,
            "truckCount": truckCounter,
            "sessionCount": sessionCounter,
            "products": products_output,
            "total": total
        })

        return output_json

    except (HTTPError, ConnectionError, JSONDecodeError):
        return mocked_json