Beispiel #1
0
def put_inventory_container():
    """
    (PUT: inventory/container)
    """
    container_id = coerce_bson_id(request.form.get("container_id"))
    inventory.add_to_inventory(container_id)
    return jsonify({"status": "ok"})
Beispiel #2
0
def get(item_id):
    """
    Get item from id
    """
    coll = Item.collection()
    dic = coll.find_one({"_id": coerce_bson_id(item_id)})
    return Item.unserialize(dic) if dic is not None else None
Beispiel #3
0
def put_order():
    """
    (PUT: order)
    """
    items_lis = json.loads(request.form.get("items"))
    admin_notes = request.form.get("admin_notes")
    user_notes = request.form.get("user_notes")
    status = request.form.get("status")
    user_id = request.form.get("user_id")
    admin_id = request.form.get("admin_id")
    id = request.form.get("_id")

    #actionables
    apply_shipping_id = request.form.get("shipping_method", None)
    apply_coupon_code = request.form.get("apply_coupon", None)
    apply_debits_credits = request.form.get("apply_debits_credits", False)
    if apply_debits_credits == "false":
        apply_coupon_code = False
    elif apply_debits_credits == "true":
        apply_coupon_code = True

    o = orders.Order()
    print id
    if id is not None:
        o = orders.get(coerce_bson_id(id))
    o.user_id = user_id
    o.status = status
    o.items = [{"obj_id": coerce_bson_id(x["obj_id"]), "quantity": float(x["quantity"])} for x in items_lis]
    o.request_notes = user_notes
    o.admin_notes = admin_notes
    o.admin_id = admin_id
    if apply_shipping_id is not None and len(apply_shipping_id) > 0:
        apply_shipping(o, apply_shipping_id)
    if apply_coupon_code is not None and len(apply_coupon_code) > 0:
        apply_coupon(o, apply_coupon_code)

    if apply_debits_credits:
        #apply taxes and discounts
        apply_discounts(o)
        apply_tax(o)

    o.save()

    return jsonify({
        "status": "ok",
    })
Beispiel #4
0
def del_campaign():
    """
    (DELETE: /campaign)
    """
    from campaigns.campaign.model import Campaign
    from unifide_backend.action.social.facebook.model import FBPost, FBEvent
    from unifide_backend.action.social.twitter.model import TWTweet
    from unifide_backend.action.social.foursquare.model import FSQPageUpdate
    from unifide_backend.action.mapping.action import del_mapping, get_brand_mapping, get_mapping
    from unifide_backend.action.social.facebook.action import del_fb_post, del_fb_event
    from unifide_backend.action.social.twitter.action import del_tweet
    from unifide_backend.action.social.foursquare.action import del_fsq_update

    user_id = request.args.get("user_id")
    brand_name = request.args.get("brand_name")
    campaigns = request.args.get("campaign_list")

    brand_obj = get_brand_mapping(user_id, brand_name)

    campaign_list = campaigns.split(',')
    for c in campaign_list:
        mapping_obj = get_mapping(c)

        # delete facebook post / event
        if mapping_obj.facebook is not None:
            id = mapping_obj.facebook
            post = FBPost.collection().find_one({"_id": coerce_bson_id(id)})
            try:
                if post is not None:
                    del_fb_post(post["post_id"], id, brand_obj.facebook["access_token"])
                event = FBEvent.collection().find_one({"_id": coerce_bson_id(id)})
                if event is not None:
                    del_fb_event(event["event_id"], id, brand_obj.facebook["access_token"])
            except Exception, err:
                print traceback.format_exc()
                print id

        # delete twitter status
        if mapping_obj.twitter is not None:
            id = mapping_obj.twitter
            tweet = TWTweet.collection().find_one({"_id": coerce_bson_id(id)})
            try:
                del_tweet(tweet["fields"]["id_str"] if tweet["fields"] is not None else None, id, brand_obj.twitter["access_token"]["key"], brand_obj.twitter["access_token"]["secret"])
            except Exception, err:
                print traceback.format_exc()
                print id
Beispiel #5
0
def get_container(container_id):
    """
    Given container id, return container object.
    None if nothing found.
    """
    coll = Container.collection()
    dic = coll.find_one({"_id": coerce_bson_id(container_id)})
    return Container.unserialize(dic) if dic is not None else None
Beispiel #6
0
def _new_discount(
    admin_id,
    amount,
    applicable_on,
    begins_on,
    container_id,
    description,
    discount_type,
    duration,
    ends_on,
    item_id,
    min_order,
    name,
):
    # create discount obj
    discount_obj = discounts.Discount()
    discount_obj.name = name
    discount_obj.description = description
    discount_obj.status = discounts.DiscountStatus.ENABLED
    discount_obj.admin_id = admin_id
    discount_obj.discount_scope = discounts.DiscountScope.ALL_ITEMS
    if applicable_on == "item":
        discount_obj.discount_scope = discounts.DiscountScope.ITEM_ONLY
        discount_obj.obj_id = coerce_bson_id(item_id)
        discount_obj.coll_name = items.Item.coll_name()
    elif applicable_on == "container":
        discount_obj.discount_scope = discounts.DiscountScope.CONTAINER_WIDE
        discount_obj.obj_id = coerce_bson_id(container_id)
        discount_obj.coll_name = items.Container.coll_name()
    if discount_type == "percentage":
        discount_obj.discount_percentage = float(amount)
    elif discount_type == "absolute":
        discount_obj.absolute_discounted_price = float(amount)
    discount_obj.order_minimum_spending = float(min_order)
    discount_obj.discount_lifetime_type = discounts.DiscountLifetime.FOREVER
    if duration == "duration":
        discount_obj.discount_lifetime_type = discounts.DiscountLifetime.LIMITED
        discount_obj.begins_utc_datetime = datetime.fromtimestamp(
            mktime(datetime.utctimetuple(datetime.strptime(begins_on, "%d/%m/%Y")))
        )
        discount_obj.expire_utc_datetime = datetime.fromtimestamp(
            mktime(datetime.utctimetuple(datetime.strptime(ends_on, "%d/%m/%Y")))
        )
    discount_obj._id = discount_obj.save()
    return discount_obj
Beispiel #7
0
def get(comment_id):
    """
    Return the comment object given the id

    :param comment_id:
    """
    dic = Comment.collection().find_one({
        "_id": coerce_bson_id(comment_id)
    })
    return Comment.unserialize(dic) if dic is not None else None
Beispiel #8
0
def del_fsq_update(update_id, obj_id, access_token):
    if update_id is not None:
        url = "%s/%s/%s" % ('pageupdates', update_id, 'delete')
        api = FoursquareAPI(access_token)

        dict = {"update_id": update_id}

        data = api.request(url, post_args=dict)
        print data

    FSQPageUpdate.collection().update({"_id": coerce_bson_id(obj_id)}, {"$set": {"is_deleted": 1}})
Beispiel #9
0
def get(campaign_obj_id):
    """
    Gets a campaign with the given id

    :param campaign_obj_id:
    :return:
    """
    collection = Campaign.collection()
    if campaign_obj_id is None:
        return None
    dic = collection.find_one({"_id": coerce_bson_id(campaign_obj_id)})
    return Campaign.unserialize(dic) if dic is not None else None
Beispiel #10
0
def new_coupon(admin_id, amount, applicable_on, begins_on, container_id, coupon_type, description, ends_on, item_id,
               lifetime_type, min_spending, name, user_applicable, user_groups, user_id, valid_times, coupon_code):
    c = Coupon()
    c.coupon_scope = coupons.CouponScope.ALL_ITEMS
    if applicable_on == "item":
        c.coupon_scope = coupons.CouponScope.ITEM_ONLY
        c.obj_id = coerce_bson_id(item_id)
        c.coll_name = items.Item.coll_name()
    elif applicable_on == "container":
        c.coupon_scope = coupons.CouponScope.CONTAINER_WIDE
        c.obj_id = coerce_bson_id(container_id)
        c.coll_name = items.Container.coll_name()
    if coupon_type == "percentage":
        c.coupon_percentage_off = amount
    elif coupon_type == "absolute":
        c.coupon_value = amount
    c.valid_times = valid_times
    c.order_minimum_spending = min_spending
    c.coupon_lifetime_type = coupons.CouponLifetime.FOREVER
    if lifetime_type == "duration":
        c.coupon_lifetime_type = coupons.CouponLifetime.LIMITED
        c.begins_utc_datetime = datetime.fromtimestamp(
            mktime(datetime.utctimetuple(datetime.strptime(begins_on, "%d/%m/%Y"))))
        c.expire_utc_datetime = c.begins_utc_datetime = datetime.fromtimestamp(
            mktime(datetime.utctimetuple(datetime.strptime(ends_on, "%d/%m/%Y"))))
    c.user_scope = coupons.CouponUserScope.ALL
    if user_applicable == "group":
        c.user_scope = coupons.CouponUserScope.GROUP
        c.user_group = user_groups
    elif user_applicable == "user_specific":
        c.user_id = coerce_bson_id(user_id)
        c.user_scope = coupons.CouponUserScope.SPECIFIC
    c.name = name
    c.description = description
    c.status = coupons.CouponStatus.AVAILABLE
    c.admin_id = admin_id
    c.coupon_code = coupon_code
    c.save()
Beispiel #11
0
def update_campaign_data():
    """
    (PUT: /campaign/date/update)
    """
    from campaigns.campaign.model import Campaign
    from unifide_backend.action.mapping.action import get_brand_mapping, get_mapping
    from unifide_backend.action.social.facebook.model import FBEvent
    from unifide_backend.action.social.facebook.action import update_fb_event

    user_id = request.form.get("user_id")
    brand_name = request.form.get("brand_name")
    campaign_id = request.form.get('campaign_id')
    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
    place = request.form.get("place")
    item_list = request.form.get("item_list")
    print title, description
    print campaign_id
    brand_obj = get_brand_mapping(user_id, brand_name)
    mapping_obj = get_mapping(campaign_id)
    print brand_obj
    print mapping_obj

    set_dic = {
        "title": title,
        "description": description,
        "happening_datetime_start": event_datetime_start,
        "happening_datetime_end": event_datetime_end,
    }
    if item_list is not None and len(item_list) > 0:
        set_dic["item_id_lis"] = item_list

    if mapping_obj.campaign is not None:
        Campaign.collection().update({"_id": mapping_obj.campaign},
                                     {"$set" : set_dic})
    if mapping_obj.blog is not None:
        Campaign.collection().update({"_id": mapping_obj.blog},
                                     {"$set" : set_dic})
    if mapping_obj.facebook is not None and mapping_obj.type == "event":
        event = FBEvent.collection().find_one({"_id": coerce_bson_id(mapping_obj.facebook)})
        update_fb_event(event["event_id"], brand_obj.facebook, mapping_obj.state, title, description, event_datetime_start, event_datetime_end)

    return jsonify({"status": "ok"})
Beispiel #12
0
def get_item_url():
    """
    (GET: /campaign/item/url)
    """
    from base.media.action import url_for
    from base.media.model import Media
    from base.items.model import Item

    obj_id = request.args.get("obj_id")
    item_obj = Item.unserialize(Item.collection().find_one({"_id": coerce_bson_id(obj_id)}))
    media_obj = Media.unserialize(Media.collection().find_one({"_id": item_obj.media_id}))

    if media_obj is None:
        return jsonify({"status": "error",
                        "error": "No item found"})
    item_url = url_for(media_obj)

    return jsonify({"status": "ok",
                    "url": item_url})
Beispiel #13
0
def put_user():
    """
    (PUT: user)
    """
    _id = coerce_bson_id(request.form.get("_id"))
    username = request.form.get("username")
    email = request.form.get("email")
    password = request.form.get("password")
    first_name = request.form.get("first_name")
    middle_name = request.form.get("middle_name")
    last_name = request.form.get("last_name")
    address = request.form.get("address")
    user_groups = json.loads(request.form.get("user_groups"))
    status = request.form.get("status")

    new_user(_id, address, email, first_name, last_name, middle_name, password, status, user_groups, username)

    return jsonify({
        "status": "ok",
    })
Beispiel #14
0
def apply_discounts(order_obj):
    """
    Given an order, updates the order with prevailing discount rules
    onto the order's debit attribute
    """
    all_dedits = order_obj.debits
    other_debit = filter(lambda x: x["coll_name"] != discounts.Discount.coll_name(), all_dedits)
    all_discounts = discounts.get_all()
    valid_discounts = []
    for item_dic in order_obj.items:
        for d in all_discounts:
            item_obj = items.get(coerce_bson_id(item_dic["obj_id"]))
            if item_obj is None: continue
            if discounts.valid_on_item(d, item_obj):
                valid_discounts += [{
                                        "obj_id": d._id,
                                        "coll_name": discounts.Discount.coll_name(),
                                        "amount": discounts.discounted_value(item_obj.price, d),
                                    }]
                break
    order_obj.debits = other_debit + valid_discounts
    return valid_discounts
Beispiel #15
0
def remove_container(container_id):
    coll = Container.collection()
    coll.remove({"_id": coerce_bson_id(container_id)})
Beispiel #16
0
def remove(item_id):
    """
    Delete item from id
    """
    coll = Item.collection()
    coll.remove({"_id": coerce_bson_id(item_id)})
Beispiel #17
0
def get(id):
    coll = Media.collection()
    dic = coll.find_one({"_id": coerce_bson_id(id)})
    return Media.unserialize(dic) if dic is not None else None
Beispiel #18
0
                print id

        # delete twitter status
        if mapping_obj.twitter is not None:
            id = mapping_obj.twitter
            tweet = TWTweet.collection().find_one({"_id": coerce_bson_id(id)})
            try:
                del_tweet(tweet["fields"]["id_str"] if tweet["fields"] is not None else None, id, brand_obj.twitter["access_token"]["key"], brand_obj.twitter["access_token"]["secret"])
            except Exception, err:
                print traceback.format_exc()
                print id

        # delete foursquare page update
        if mapping_obj.foursquare is not None:
            id = mapping_obj.foursquare
            page_update = FSQPageUpdate.collection().find_one({"_id": coerce_bson_id(id)})
            try:
                del_fsq_update(page_update["update_id"] if page_update["update_id"] is not None else None, id, brand_obj.foursquare["access_token"])
            except Exception, err:
                print traceback.format_exc()
                print id

        # delete campaign
        if mapping_obj.campaign is not None:
            id = mapping_obj.campaign
            Campaign.collection().remove({"_id": coerce_bson_id(id)})

        # delete blog
        if mapping_obj.blog is not None:
            id = mapping_obj.blog
            Campaign.collection().remove({"_id": coerce_bson_id(id)})
Beispiel #19
0
def del_tweet(id_str, obj_id, key, secret):
    if id_str is not None:
        api = get_api(key, secret)[0]
        data = api.destroy_status(id=long(id_str))
        print data
    TWTweet.collection().update({"_id": coerce_bson_id(obj_id)}, {"$set": {"is_deleted": 1}})
Beispiel #20
0
def del_mapping(mapping_obj_id):
    collection = Mapping.collection()
    if mapping_obj_id is None:
        return None
    dic = collection.update({"_id": coerce_bson_id(mapping_obj_id)}, {"$set": {"is_deleted": 1} })
Beispiel #21
0
def del_fb_event(event_id, obj_id, access_token):
    if event_id is not None:
        data = GraphAPI(access_token).delete_object(event_id)
        print data
    FBEvent.collection().update({"_id": coerce_bson_id(obj_id)}, {"$set": {"is_deleted": 1}})
Beispiel #22
0
def get_mapping(mapping_obj_id):
    collection = Mapping.collection()
    if mapping_obj_id is None:
        return None
    dic = collection.find_one({"_id": coerce_bson_id(mapping_obj_id)})
    return Mapping.unserialize(dic) if dic is not None else None
Beispiel #23
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"})
Beispiel #24
0
def get_brand_platform_id(user_id, brand_id, platform):
    dic = BrandMapping.collection().find_one({"uid": user_id, "_id": coerce_bson_id(brand_id)})
    brand = BrandMapping.unserialize(dic) if dic is not None else None
    return getattr(brand, platform)
Beispiel #25
0
def get(shipping_rule_id):
    dic = ShippingRule.collection().find_one({"_id": coerce_bson_id(shipping_rule_id)})
    return ShippingRule.unserialize(dic) if dic is not None else None