Пример #1
0
def create_item_containers(container_dic):
    for name, dic in container_dic.items():
        container_obj = items.container_from_path(items.container_path(dic["path_lis"]))
        if container_obj is None:
            save_container_path(dic["path_lis"], dic["description"])
        if "children" in dic:
            create_item_containers(dic["children"])
Пример #2
0
def gen_discounts(model, existing_path_lis=[]):
    """
    Generate discounts for individual containers from a model
    """
    if existing_path_lis is None: existing_path_lis = []

    for container_name, attr_dic in model.items():
        path_lis = existing_path_lis + [container_name]
        container_obj = items.container_from_path(path_lis)

        discount_obj = Discount()
        discount_obj.coll_name = items.Container.coll_name()
        discount_obj.obj_id = container_obj._id
        discount_obj.discount_lifetime_type = DiscountLifetime.FOREVER
        discount_obj.name = loremipsum.sentence(max_char=30)
        discount_obj.description = loremipsum.paragraph()
        discount_obj.status = DiscountStatus.ENABLED

        if ContainerAttr.DISCOUNT_PERCENTAGE in attr_dic:
            perc = attr_dic[ContainerAttr.DISCOUNT_PERCENTAGE]
            discount_obj.discount_percentage = perc
            discount_obj.save()

        if ContainerAttr.DISCOUNT_ABSOLUTE in attr_dic:
            amount = attr_dic[ContainerAttr.DISCOUNT_ABSOLUTE]
            discount_obj.absolute_discounted_price = amount
            discount_obj.save()

        #gen recursive models
        if "containers" in model: gen_discounts(model["containers"], path_lis)
Пример #3
0
def showcase():
    #get menu items
    menu_path = ["Menu", "Food", "Mains"]
    all_items = items.get_all(items.container_from_path(menu_path))

    return render_template("showcase.html",
        **{
            "items": all_items,
        })
Пример #4
0
def save(org_info_obj):
    """
    Saves `OrgInfo` object
    """
    container_obj = __get_or_create_org_container()
    all_org_items = items.get_all(items.container_from_path(ORG_PATH))
    for k, v in vars(org_info_obj).items():
        existing_item = __has_item(all_org_items, k)
        if existing_item:
            if existing_item.description != v:
                existing_item.description = v
                items.save(existing_item)
        else:
            container_obj = items.container_from_path(ORG_PATH)
            item_obj = Item.unserialize({
                "name": k,
                "description": v,
                "container_id": container_obj.obj_id(),
            })
            items.save(item_obj)
Пример #5
0
def gen_model(model, existing_path_lis=None):
    if existing_path_lis is None: existing_path_lis = []

    if Generate.ITEMS_CONTAINERS == model:
        max_depth = choice(range(1, 3))
        to_gen = _spawn_items_containers(existing_path_lis)
        for g in to_gen:
            depth = len(g) - len(existing_path_lis)
            if depth > max_depth: break
            to_gen += _spawn_items_containers(g)
        return

    for container_name, attr_dic in model.items():
        #save container
        path_lis = existing_path_lis + [container_name]

        #only create if container doesnt already exists
        if items.container_from_path(path_lis) is None:
            container_obj = save_container_path(path_lis)
            if ContainerAttr.DESCRIPTION in model: container_obj.description = model[ContainerAttr.DESCRIPTION]
            container_obj.save()

            #create items
            if "items" in model:
                for item in model["items"]:
                    custom_type = item["custom"] if "custom" in item else None
                    if custom_type is None:
                        i = Item(**{item})
                        i.container_id = container_from_path(existing_path_lis)
                        i.save()
                    elif custom_type == Generate.ITEMS_ONLY:
                        all_items = _spawn_items(existing_path_lis)
                        custom_attr = item["custom_attr"] if "custom_attr" in item else {}
                        for k, v in custom_attr:
                            for new_item in all_items:
                                setattr(new_item, k, v)
                        map(lambda x: x.save(), all_items)

        #gen recursive models
        if "containers" in attr_dic:
            gen_model(attr_dic["containers"], path_lis)
Пример #6
0
def _spawn_items(pl):
    items_to_cr8 = [loremipsum.sentence(30) for _ in range(choice(range(10, 20)))]
    all_items = []
    for item_name in items_to_cr8:
        i = Item()
        i.name = item_name
        i.description = loremipsum.paragraph()
        i.price = choice(range(1, 100))
        i.container_id = container_from_path(pl)._id
        i._id = i.save()
        all_items += [i]
    return all_items
Пример #7
0
def _spawn_items_containers(pl):
    containers_to_cr8 = [loremipsum.sentence(30) for _ in range(choice(range(1, 3)))]
    all_pl = map(lambda x: pl + [x], containers_to_cr8)
    items_to_cr8 = [loremipsum.sentence(30) for _ in range(choice(range(5, 10)))]

    for item_name in items_to_cr8:
        i = Item()
        i.name = item_name
        i.description = loremipsum.paragraph()
        i.price = choice(range(1, 100))
        i.container_id = container_from_path(pl)._id
        i.save()
    for container_pl_to_cr8 in all_pl:
        save_container_path(container_pl_to_cr8)
    return all_pl
Пример #8
0
def get_containers_and_items():
    """
    (GET: container+item)

    Fetches the immediate child containers of a path, as well as the items in the specified container.
    """
    path_lis_json_str = request.args.get("path_lis")
    path_lis = json.loads(path_lis_json_str) if path_lis_json_str is not None else None
    container_obj = items.container_from_path(path_lis)
    all_items = items.get_all(container_obj)
    all_child_containers = items.child_containers(container_obj)
    return jsonify({
        "status": "ok",
        "description": container_obj.description if container_obj is not None else None,
        "items": [x.serialize(json_friendly=True) for x in all_items],
        "child_containers": [x.serialize(json_friendly=True) for x in all_child_containers]
    })
Пример #9
0
def gen_items(total_items=5):
    container_obj = items.container_from_path(GEN_ITEM_PATH_LIS)
    if container_obj is None:
        container_obj = items.save_container_path(GEN_ITEM_PATH_LIS)

    item_lis = []
    for _ in range(total_items):
        dic = {
            "name": loremipsum.sentence(max_char=choice(range(10, 20))),
            "media": None,
            "description": loremipsum.paragraph(max_char=choice(range(40, 100))),
            "quantity": choice(range(1, 20)),
            "price": choice(range(1, 20)),
            "container_id": container_obj.obj_id(),
        }
        item_obj = items.Item.unserialize(dic)
        item_obj._id = items.save(item_obj)
        item_lis += [item_obj]

    return item_lis
Пример #10
0
def put_campaign_data():
    """
    (PUT: campaign/data)
    """
    from campaigns.campaign.model import Campaign, CampaignType
    from campaigns.campaign.action import save
    from unifide_backend.action.mapping.model import CampaignState
    from unifide_backend.action.mapping.action import put_mapping, get_brand_mapping
    from unifide_backend.action.social.facebook.action import put_fb_post, get_fb_user, put_fb_event
    from unifide_backend.action.social.twitter.action import put_tweet, get_tw_user
    from unifide_backend.action.social.foursquare.action import put_fsq_update
    from base.media.action import _store_locally, url_for, save_media
    from base.media.model import Media
    from base.items.action import save as save_item
    from base import items
    from base.items.model import Item
    from unifide_backend.action.util import url_generator
    from cfg import DOMAIN_PATH

    print "starting"
    user_id = request.form.get("user_id")
    brand_name = request.form.get("brand_name")
    platforms = request.form.getlist("platforms")
    type = request.form.get("type")
    title = request.form.get("title")
    description = request.form.get("description")
    event_datetime_start = float(request.form.get("datetime_start")) if request.form.get("datetime_start") is not None else None
    event_datetime_end = float(request.form.get("datetime_end")) if request.form.get("datetime_end") is not None else None
    item_file_id = request.form.get("media_file_url", None)
    state = request.form.get("state")
    scheduled_datetime = float(request.form.get("scheduled_datetime")) if state == CampaignState.SCHEDULED else None
    redirect_url = request.form.get("redirect_to", None)

    brand_obj = get_brand_mapping(user_id, brand_name)

    parsed_title = title
    parsed_description = description
    image_io = None
    file_path = None
    media_obj = None

    # load media object from item ID
    if item_file_id:
        dic = Item.collection().find_one({"_id": coerce_bson_id(item_file_id)})
        item_obj = Item.unserialize(dic) if dic is not None else None
        if item_obj:
            media_obj = Media.unserialize(Media.collection().find_one({"_id": item_obj.media_id}))

    # load user uploaded image
    files = ["media_file"]
    for f in files:
        media_file = request.files.get(f)
        if media_file.filename != "":
            if request.files.get("media_file").mimetype in ["image/png", "image/gif", "image/jpeg", "image/jpg"]:
                file_path = _store_locally(media_file.filename, media_file)
                media_obj = save_media(media_file)

    # open file stream to user uploaded image
    if file_path:
        image = Image.open(file_path)
        image_io = StringIO()
        image.save(image_io, 'jpeg', quality=95)
        image_io.seek(0)

    # open file stream to item image
    if media_obj:
        if media_obj.storage == MediaStorage.LOCAL:
            img_file_path = os.path.join(UPLOAD_FOLDER, media_obj.file_name)
            image = Image.open(img_file_path)
        else:
            req = requests.open(url_for(media_obj))
            image = Image.open(StringIO(req.content))
        image_io = StringIO()
        image.save(image_io, 'jpeg', quality=95)
        image_io.seek(0)

    kvp = {}

    if PLATFORM_CAMPAIGN in platforms:
        c = Campaign()
        c.uid = user_id
        c.title = title
        c.description = description
        c.type = type
        if item_file_id is not None:
            c.item_id_lis.append(item_file_id)
        #event component
        c.happening_datetime_start = event_datetime_start if event_datetime_start is not None else None
        c.happening_datetime_end = event_datetime_end if event_datetime_end is not None else None
        c._id = save(c)
        kvp["campaign"] = c._id
        print "done campaign"

    if PLATFORM_BLOG in platforms:
        blog = Item()
        blog.name = title
        blog.description = description
        blog.media_id = media_obj._id if media_obj is not None else None

        blog_path_list = ["Pages", "Blog"]
        blog_container = items.container_from_path(blog_path_list)
        blog.container_id = blog_container._id

        blog._id = save_item(blog)
        kvp["blog"] = blog._id
        print "done blog"

    # add a link to web/blog campaign for social network campaigns
    if PLATFORM_CAMPAIGN in platforms or PLATFORM_BLOG in platforms:
        parsed_title += "\n" + url_generator(DOMAIN_PATH, title)
        parsed_description += "\n\n" + url_generator(DOMAIN_PATH, title)

    if PLATFORM_FACEBOOK in platforms:
        fb_user = get_fb_user(user_id, brand_name)
        if type == CampaignType.PROMOTION:
            post = put_fb_post(brand_obj.facebook, fb_user.fb_id, state, parsed_title, image_io)
            kvp[PLATFORM_FACEBOOK] = post._id
        elif type == CampaignType.EVENT:
            event = put_fb_event(brand_obj.facebook, fb_user.fb_id, state, title, parsed_description, event_datetime_start, event_datetime_end, image_io)
            kvp[PLATFORM_FACEBOOK] = event._id
        print "done facebook"

    if PLATFORM_TWITTER in platforms:
        tw_user = get_tw_user(user_id, brand_name)[0]
        tweet = put_tweet(parsed_title, tw_user.tw_id, brand_obj.twitter["access_token"]["key"], brand_obj.twitter["access_token"]["secret"], state, url_for(media_obj) if media_obj is not None else file_path)
        kvp[PLATFORM_TWITTER] = tweet._id
        print "done twitter"

    if PLATFORM_FOURSQUARE in platforms:
        page_update = put_fsq_update(parsed_title, brand_obj.foursquare["venues"][0], brand_obj.foursquare["access_token"], state)
        kvp[PLATFORM_FOURSQUARE] = page_update._id
        print "done foursquare"

    if PLATFORM_PUSH in platforms:
        kvp[PLATFORM_PUSH] = 1
        #todo : waiting for push implementation
        pass

    publish_datetime = datetime.datetime.now() if state == CampaignState.PUBLISHED else datetime.datetime.fromtimestamp(scheduled_datetime)
    put_mapping(user_id, brand_name, kvp, publish_datetime, type, state)

    if redirect_url is not None:
        return render_template("redirect.html", **{
            "redirect_url": redirect_url
        })

    return jsonify({"status": "ok"})
Пример #11
0
def __container_obj():
    return items.container_from_path(ARTICLE_PATH)
Пример #12
0
def __get_or_create_org_container():
    container_obj = items.container_from_path(ORG_PATH)
    if container_obj is None:
        items.save_container_path([ORG_PATH])
        container_obj = items.container_from_path(ORG_PATH)
    return container_obj