def batch_patch(id):
    try:
        # must be batch patch, where json["id"] is prefixed and equals id
        json = batch_patch_schema.extend({"id": All(prefixed_id("BAT"),
                                                    id)})(request.json)
        forced = forced_schema(request.args).get("force")
    except MultipleInvalid as e:
        return problem.invalid_params_response(e)

    existing_batch = Batch.from_mongodb_doc(db.batch.find_one({"_id": id}))
    if not existing_batch:
        return problem.missing_batch_response(id)

    if json.get("sku_id"):
        existing_sku = db.sku.find_one({"_id": json['sku_id']})
        if not existing_sku:
            return problem.invalid_params_response(
                problem.missing_resource_param_error(
                    "sku_id", "must be an existing sku id"))

    if (existing_batch.sku_id and "sku_id" in json
            and existing_batch.sku_id != json["sku_id"] and not forced):
        return problem.dangerous_operation_unforced_response(
            "sku_id",
            "The sku of this batch has already been set. Can not change without force=true."
        )

    if "props" in json.keys():
        db.batch.update_one({"_id": id}, {"$set": {"props": json['props']}})
    if "name" in json.keys():
        db.batch.update_one({"_id": id}, {"$set": {"name": json['name']}})

    if "sku_id" in json.keys():
        db.batch.update_one({"_id": id}, {"$set": {"sku_id": json['sku_id']}})

    if "owned_codes" in json.keys():
        db.batch.update_one({"_id": id},
                            {"$set": {
                                "owned_codes": json['owned_codes']
                            }})
    if "associated_codes" in json.keys():
        db.batch.update_one(
            {"_id": id},
            {"$set": {
                "associated_codes": json['associated_codes']
            }})

    updated_batch = Batch.from_mongodb_doc(db.batch.find_one({"_id": id}))
    return BatchEndpoint.from_batch(updated_batch).redirect_response(False)
def batch_get(id):
    existing = Batch.from_mongodb_doc(db.batch.find_one({"_id": id}))

    if not existing:
        return problem.missing_batch_response(id)
    else:
        return BatchEndpoint.from_batch(existing).get_response()
def batch_bins_get(id):
    resp = Response()
    existing = Batch.from_mongodb_doc(db.batch.find_one({"_id": id}))

    if not existing:
        return problem.missing_batch_response(id)
    return BatchBinsEndpoint.from_id(id, retrieve=True).get_response()
def batch_delete(id):
    existing = Batch.from_mongodb_doc(db.batch.find_one({"_id": id}))
    if not existing:
        return problem.missing_batch_response(id)
    else:
        db.batch.delete_one({"_id": id})
        return BatchEndpoint.from_batch(existing).deleted_success_response()
Exemple #5
0
def sku_batches_get(id):
    resp = Response()

    existing = Sku.from_mongodb_doc(db.sku.find_one({"_id": id}))
    if not existing:
        resp.status_code = 404
        resp.mimetype = "application/problem+json"
        resp.data = json.dumps({
            "type":
            "missing-resource",
            "title":
            "Can not get batches for a sku that does not exist.",
            "invalid-params": [{
                "name": "id",
                "reason": "must be an exisiting sku id"
            }]
        })
        return resp

    batches = [
        Batch.from_mongodb_doc(bson).id
        for bson in db.batch.find({"sku_id": id})
    ]
    resp.mimetype = "application/json"
    resp.data = json.dumps({"state": batches})

    return resp
def search():
    query = request.args['query']
    limit = getIntArgs(request.args, "limit", 20)
    startingFrom = getIntArgs(request.args, "startingFrom", 0)
    resp = Response()

    results = []

    # debug flags
    if query == '!ALL':
        results.extend([Sku.from_mongodb_doc(e) for e in db.sku.find()])
        results.extend([Batch.from_mongodb_doc(e) for e in db.batch.find()])
        results.extend([Bin.from_mongodb_doc(e) for e in db.bin.find()])
    if query == '!BINS':
        results.extend([Bin.from_mongodb_doc(e) for e in db.bin.find()])
    if query == '!SKUS':
        results.extend([Sku.from_mongodb_doc(e) for e in db.sku.find()])
    if query == '!BATCHES':
        results.extend([Batch.from_mongodb_doc(e) for e in db.batch.find()])

    # search by label
    if query.startswith('SKU'):
        results.append(Sku.from_mongodb_doc(db.sku.find_one({'_id': query})))
    if query.startswith('BIN'):
        results.append(Bin.from_mongodb_doc(db.bin.find_one({'_id': query})))
    if query.startswith('BAT'):
        results.append(
            Batch.from_mongodb_doc(db.batch.find_one({'_id': query})))
    results = [result for result in results if result != None]

    # search for skus with owned_codes
    cursor = db.sku.find({"owned_codes": query})
    for sku_doc in cursor:
        results.append(Sku.from_mongodb_doc(sku_doc))

    # search for skus with associated codes
    cursor = db.sku.find({"associated_codes": query})
    for sku_doc in cursor:
        results.append(Sku.from_mongodb_doc(sku_doc))

    # search for skus with owned_codes
    cursor = db.batch.find({"owned_codes": query})
    for batch_doc in cursor:
        results.append(Batch.from_mongodb_doc(batch_doc))

    # search for batchs with associated codes
    cursor = db.batch.find({"associated_codes": query})
    for batch_doc in cursor:
        results.append(Batch.from_mongodb_doc(batch_doc))

    # if not DEV_ENV: # maybe use global flag + env variable instead. Shouldn't need to check this every time in production/
    if "name_text" in db.sku.index_information().keys():
        cursor = db.sku.find({"$text": {"$search": query}})
        for sku_doc in cursor:
            results.append(Sku.from_mongodb_doc(sku_doc))
    if "name_text" in db.batch.index_information().keys():
        cursor = db.batch.find({"$text": {"$search": query}})
        for batch_doc in cursor:
            results.append(Batch.from_mongodb_doc(batch_doc))

    if results != []:
        paged = results[startingFrom:(startingFrom + limit)]
        resp.status_code = 200
        resp.mimetype = "application/json"
        # TODO: Add next page / prev page operations
        resp.data = json.dumps(
            {
                'state': {
                    "total_num_results": len(results),
                    "starting_from": startingFrom,
                    "limit": limit,
                    "returned_num_results": len(paged),
                    "results": paged
                },
                "operations": []
            },
            cls=Encoder)
        return resp

    resp.status_code = 200
    resp.mimetype = "application/json"
    resp.data = json.dumps(
        {
            'state': {
                "total_num_results": len(results),
                "starting_from": startingFrom,
                "limit": limit,
                "returned_num_results": 0,
                "results": []
            },
            "operations": []
        },
        cls=Encoder)
    return resp
def bin_contents_post(id):
    into_bin = Bin.from_mongodb_doc(db.bin.find_one({"_id": id}))
    item_id = request.json['id']
    quantity = request.json['quantity']
    resp = Response()
    resp.headers.add("Cache-Control", "no-cache")

    if not into_bin:
        resp.status_code = 404
        resp.mimetype = "application/problem+json"
        resp.data = json.dumps({
            "type":
            "missing-resource",
            "title":
            "Can not receive items into a bin that does not exist.",
            "invalid-params": [{
                "name": "id",
                "reason": "must be an exisiting bin id"
            }]
        })
        return resp

    if item_id.startswith("SKU"):
        exisiting_sku = Sku.from_mongodb_doc(db.sku.find_one({"_id": item_id}))
        if not exisiting_sku:
            resp.status_code = 409
            resp.mimetype = "application/problem+json"
            resp.data = json.dumps({
                "type":
                "missing-resource",
                "title":
                "Can not receive sku that does not exist.",
                "invalid-params": [{
                    "name":
                    "item_id",
                    "reason":
                    "must be an exisiting batch or sku id"
                }]
            })
            return resp
        else:
            db.bin.update_one({"_id": into_bin.id},
                              {"$inc": {
                                  f"contents.{item_id}": quantity
                              }})
            resp.status_code = 201
            return resp
    elif item_id.startswith("BAT"):
        existing_batch = Batch.from_mongodb_doc(
            db.batch.find_one({"_id": item_id}))
        if not existing_batch:
            resp.status_code = 409
            resp.mimetype = "application/problem+json"
            resp.data = json.dumps({
                "type":
                "missing-resource",
                "title":
                "Can not receive batch that does not exist.",
                "invalid-params": [{
                    "name":
                    "item_id",
                    "reason":
                    "must be an exisiting batch or sku id"
                }]
            })
            return resp
        else:
            db.bin.update_one({"_id": into_bin.id},
                              {"$inc": {
                                  f"contents.{item_id}": quantity
                              }})
            resp.status_code = 201
            return resp
    else:
        resp.status_code = 409
        resp.mimetype = "application/problem+json"
        resp.data = json.dumps({
            "type":
            "bad-id-format",
            "title":
            "Received item id must be a batch or sku.",
            "invalid-params": [{
                "name": "item_id",
                "reason": "must be an exisiting batch or sku id"
            }]
        })
        return resp