Esempio n. 1
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("%s-variants%s" %
                 (settings.CACHE_MIDDLEWARE_KEY_PREFIX, product_id))

    product = Product.objects.get(pk=product_id)

    # Add variant(s)
    #variant_simple_form = ProductVariantSimpleForm(data=request.POST)

    # We don't have to check whether the form is valid. If the fields
    # are empty we create default ones.

    variants_count = product.variants.count()

    # First we need to prepare the requested properties for the use
    # with cartesian product. That means if the keyword "all" is
    # found we collect all options of this properties.
    properties = []
    for key, value in request.POST.items():
        if key.startswith("property"):
            property_id = key.split("_")[1]
            if value == "all":
                temp = []
                for option in PropertyOption.objects.filter(
                        property=property_id):
                    temp.append("%s|%s" % (property_id, option.id))
                properties.append(temp)
            else:
                properties.append(["%s|%s" % (property_id, value)])

    # Create a variant for every requested option combination
    for i, options in enumerate(manage_utils.cartesian_product(*properties)):

        if product.has_variant(options):
            continue

        name = request.POST.get("name")
        price = request.POST.get("price")
        slug = request.POST.get("slug")

        for option in options:
            property_id, option_id = option.split("|")
            o = PropertyOption.objects.get(pk=option_id)
            if slug:
                slug += "-"
            slug += slugify(o.name)

        slug = "%s-%s" % (product.slug, slug)
        sku = "%s-%s" % (product.sku, i + 1)

        variant = None
        # need to validate the amalgamated slug to make sure it is not already in use
        try:
            variant = Product.objects.get(slug=slug)
            message = _(u"That slug is already in use. Please use another.")
        except Product.MultipleObjectsReturned:
            message = _(u"That slug is already in use. Please use another.")
        except Product.DoesNotExist:
            variant = Product(name=name,
                              slug=slug,
                              sku=sku,
                              parent=product,
                              price=price,
                              variant_position=(variants_count + i + 1) * 10,
                              sub_type=VARIANT)
            try:
                variant.save()
            except IntegrityError:
                continue
            else:
                # By default we copy the property groups of the product to
                # the variants
                for property_group in product.property_groups.all():
                    variant.property_groups.add(property_group)

            # Save the value for this product and property.
            for option in options:
                property_id, option_id = option.split("|")
                ProductPropertyValue.objects.create(
                    product=variant,
                    property_id=property_id,
                    value=option_id,
                    type=PROPERTY_VALUE_TYPE_VARIANT)
                # By default we create also the filter values as this most of
                # the users would excepct.
                if Property.objects.get(pk=property_id).filterable:
                    ProductPropertyValue.objects.create(
                        product=variant,
                        property_id=property_id,
                        value=option_id,
                        type=PROPERTY_VALUE_TYPE_FILTER)

            message = _(u"Variants have been added.")

    html = (
        ("#selectable-products-inline",
         _selectable_products_inline(request, product)),
        ("#variants", manage_variants(request, product_id, as_string=True)),
    )

    result = simplejson.dumps({
        "html": html,
        "message": message,
    },
                              cls=LazyEncoder)

    return HttpResponse(result)
Esempio n. 2
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("%s-variants%s" %
                 (settings.CACHE_MIDDLEWARE_KEY_PREFIX, product_id))

    product = Product.objects.get(pk=product_id)
    all_properties = product.get_property_select_fields()

    variant_simple_form = ProductVariantSimpleForm(
        all_properties=all_properties, data=request.POST)

    message = ''
    added_count = 0

    if variant_simple_form.is_valid():
        # Add variant(s)
        variants_count = product.variants.count()

        # First we need to prepare the requested properties for the use
        # with cartesian product. That means if the keyword "all" is
        # found we collect all options of this properties.
        properties = []
        for key, value in variant_simple_form.cleaned_data.items():
            if key.startswith("property"):
                property_id = key.split("_")[1]
                if value == "all":
                    temp = []
                    for option in PropertyOption.objects.filter(
                            property=property_id):
                        temp.append("%s|%s" % (property_id, option.id))
                    properties.append(temp)
                elif value == '':
                    continue
                else:
                    properties.append(["%s|%s" % (property_id, value)])

        # Create a variant for every requested option combination
        for i, options in enumerate(
                manage_utils.cartesian_product(*properties)):
            if product.has_variant(options, only_active=False):
                continue

            pvcf = ProductVariantCreateForm(options=options,
                                            product=product,
                                            data=request.POST)
            if pvcf.is_valid():
                variant = pvcf.save(commit=False)
                variant.sku = "%s-%s" % (product.sku, i + 1)
                variant.parent = product
                variant.variant_position = (variants_count + i + 1) * 10
                variant.sub_type = VARIANT

                try:
                    variant.save()
                    added_count += 1
                except IntegrityError:
                    continue

                # By default we copy the property groups of the product to
                # the variants
                for property_group in product.property_groups.all():
                    variant.property_groups.add(property_group)

                # Save the value for this product and property.
                for option in options:
                    property_id, option_id = option.split("|")
                    ProductPropertyValue.objects.create(
                        product=variant,
                        property_id=property_id,
                        value=option_id,
                        type=PROPERTY_VALUE_TYPE_VARIANT)
                    # By default we create also the filter values as this most of
                    # the users would expect.
                    if Property.objects.get(pk=property_id).filterable:
                        ProductPropertyValue.objects.create(
                            product=variant,
                            property_id=property_id,
                            value=option_id,
                            type=PROPERTY_VALUE_TYPE_FILTER)
            else:
                continue
        else:
            message = _(u"No variants have been added.")

            if added_count > 0:
                message = _(u"Variants have been added.")
        variant_simple_form = ProductVariantSimpleForm(
            all_properties=all_properties)

    html = (
        ("#selectable-products-inline",
         _selectable_products_inline(request, product)),
        ("#variants",
         manage_variants(request,
                         product_id,
                         as_string=True,
                         variant_simple_form=variant_simple_form)),
    )

    result = simplejson.dumps({
        "html": html,
        "message": message,
    },
                              cls=LazyEncoder)

    return HttpResponse(result)
Esempio n. 3
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("%s-variants%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, product_id))

    product = Product.objects.get(pk=product_id)

    # Add variant(s)
    variant_simple_form = ProductVariantSimpleForm(data=request.POST)

    # We don't have to check whether the form is valid. If the fields
    # are empty we create default ones.

    # First we need to prepare the requested properties for the use
    # with cartesian product. That means if the keyword "all" is
    # found we collect all options of this properties.
    properties = []
    for key, value in request.POST.items():
        if key.startswith("property"):
            property_id = key.split("_")[1]
            if value == "all":
                temp = []
                for option in PropertyOption.objects.filter(property=property_id):
                    temp.append("%s|%s" % (property_id, option.id))
                properties.append(temp)
            else:
                properties.append(["%s|%s" % (property_id, value)])

    # Create a variant for every requested option combination
    for i, options in enumerate(manage_utils.cartesian_product(*properties)):

        if product.has_variant(options):
            continue

        name = request.POST.get("name")
        price = request.POST.get("price")
        slug = request.POST.get("slug")

        for option in options:
            property_id, option_id = option.split("|")
            o = PropertyOption.objects.get(pk=option_id)
            if slug:
                slug += "-"
            slug += slugify(o.name)

        slug = "%s-%s" % (product.slug, slug)
        sku = "%s-%s" % (product.sku, i + 1)

        variant = None
        # need to validate the amalgamated slug to make sure it is not already in use
        try:
            product = Product.objects.get(slug=slug)
            message = _(u"That slug is already in use. Please use another.")
        except Product.MultipleObjectsReturned:
            message = _(u"That slug is already in use. Please use another.")
        except Product.DoesNotExist:
            variant = Product(name=name, slug=slug, sku=sku, parent=product, price=price, variant_position=(i + 1) * 10, sub_type=VARIANT)
            try:
                variant.save()
            except IntegrityError:
                continue
            else:
                # By default we copy the property groups of the product to
                # the variants
                for property_group in product.property_groups.all():
                    variant.property_groups.add(property_group)

            # Save the value for this product and property.
            for option in options:
                property_id, option_id = option.split("|")
                ProductPropertyValue.objects.create(product=variant, property_id=property_id, value=option_id, type=PROPERTY_VALUE_TYPE_VARIANT)
                # By default we create also the filter values as this most of
                # the users would excepct.
                if Property.objects.get(pk=property_id).filterable:
                    ProductPropertyValue.objects.create(product=variant, property_id=property_id, value=option_id, type=PROPERTY_VALUE_TYPE_FILTER)

            message = _(u"Variants have been added.")

    html = (
        ("#selectable-products-inline", _selectable_products_inline(request, product)),
        ("#variants", manage_variants(request, product_id, as_string=True)),
    )

    result = simplejson.dumps({
        "html": html,
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result)
Esempio n. 4
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("%s-variants%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, product_id))

    product = Product.objects.get(pk=product_id)
    all_properties = product.get_variants_properties()

    variant_simple_form = ProductVariantSimpleForm(all_properties=all_properties, data=request.POST)

    message = ""
    added_count = 0

    if variant_simple_form.is_valid():
        # Add variant(s)
        variants_count = product.variants.count()

        # First we need to prepare the requested properties for the use
        # with cartesian product. That means if the keyword "all" is
        # found we collect all options of this properties.
        properties = []
        for key, value in variant_simple_form.cleaned_data.items():
            if key.startswith("property"):
                _property, property_group_id, property_id = key.split("_")
                if value == "all":
                    temp = []
                    for option in PropertyOption.objects.filter(property=property_id):
                        temp.append("%s|%s|%s" % (property_group_id, property_id, option.id))
                    properties.append(temp)
                elif value == "":
                    continue
                else:
                    properties.append(["%s|%s|%s" % (property_group_id, property_id, value)])

        # Create a variant for every requested option combination
        for i, options in enumerate(manage_utils.cartesian_product(*properties)):
            if product.has_variant(options, only_active=False):
                continue

            pvcf = ProductVariantCreateForm(options=options, product=product, data=request.POST)
            if pvcf.is_valid():
                variant = pvcf.save(commit=False)
                variant.sku = "%s-%s" % (product.sku, i + 1)
                variant.parent = product
                variant.variant_position = (variants_count + i + 1) * 10
                variant.sub_type = VARIANT

                try:
                    variant.save()
                    added_count += 1
                except IntegrityError:
                    continue

                # By default we copy the property groups of the product to
                # the variants
                for property_group in product.property_groups.all():
                    variant.property_groups.add(property_group)

                # Save the value for this product and property.
                for option in options:
                    property_group_id, property_id, option_id = option.split("|")
                    # local properties are not bound to property groups
                    property_group_id = None if property_group_id == "0" else property_group_id
                    ProductPropertyValue.objects.create(
                        product=variant,
                        property_group_id=property_group_id,
                        property_id=property_id,
                        value=option_id,
                        type=PROPERTY_VALUE_TYPE_VARIANT,
                    )
                    # By default we create also the filter values as this most of
                    # the users would expect.
                    if Property.objects.get(pk=property_id).filterable:
                        ProductPropertyValue.objects.create(
                            product=variant,
                            property_group_id=property_group_id,
                            property_id=property_id,
                            value=option_id,
                            type=PROPERTY_VALUE_TYPE_FILTER,
                        )
            else:
                continue
        else:
            message = _(u"No variants have been added.")

            if added_count > 0:
                message = _(u"Variants have been added.")
        variant_simple_form = ProductVariantSimpleForm(all_properties=all_properties)

    html = (
        ("#selectable-products-inline", _selectable_products_inline(request, product)),
        ("#variants", manage_variants(request, product_id, as_string=True, variant_simple_form=variant_simple_form)),
    )

    result = json.dumps({"html": html, "message": message}, cls=LazyEncoder)

    return HttpResponse(result, content_type="application/json")
Esempio n. 5
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("variants%s" % product_id)

    product = Product.objects.get(pk=product_id)

    # Add variant(s)
    variant_simple_form = ProductVariantSimpleForm(data=request.POST)

    # We don't have to check whether the form is valid. If the fields
    # are empty we create default ones.

    # First we need to prepare the requested properties for the use
    # with cartesian product. That means if the keyword "all" is
    # found we collect all options of this properties.
    properties = []
    for key, value in request.POST.items():
        if key.startswith("property"):
            property_id = key.split("_")[1]
            if value == "all":
                temp = []
                for option in PropertyOption.objects.filter(property=property_id):
                    temp.append("%s|%s" % (property_id, option.id))
                properties.append(temp)
            else:
                properties.append(["%s|%s" % (property_id, value)])

    # Create a variant for every requested option combination
    for i, options in enumerate(manage_utils.cartesian_product(*properties)):

        if product.has_variant(options):
            continue

        price = request.POST.get("price")

        slug = ""
        for option in options:
            property_id, option_id = option.split("|")
            o = PropertyOption.objects.get(pk=option_id)
            slug += "-" + slugify(o.name)

        slug = "%s%s" % (product.slug, slug)
        sku = "%s-%s" % (product.sku, i+1)

        variant = Product(slug=slug, sku=sku, parent=product, price=price, variant_position=i+1, sub_type=VARIANT)
        variant.save()

        # Save the value for this product and property
        for option in options:
            property_id, option_id = option.split("|")
            pvo = ProductPropertyValue(product = variant, property_id = property_id, value=option_id)
            pvo.save()

    from lfs.manage.views.product.product import selectable_products_inline
    result = simplejson.dumps({
        "properties" : manage_variants(request, product_id, as_string=True),
    })

    return HttpResponse(result)
Esempio n. 6
0
def add_variants(request, product_id):
    """Adds variants to product with passed product_id based on property/option-
    combinations passed within request body.
    """
    cache.delete("variants%s" % product_id)

    product = Product.objects.get(pk=product_id)

    # Add variant(s)
    variant_simple_form = ProductVariantSimpleForm(data=request.POST)

    # We don't have to check whether the form is valid. If the fields
    # are empty we create default ones.

    # First we need to prepare the requested properties for the use
    # with cartesian product. That means if the keyword "all" is
    # found we collect all options of this properties.
    properties = []
    for key, value in request.POST.items():
        if key.startswith("property"):
            property_id = key.split("_")[1]
            if value == "all":
                temp = []
                for option in PropertyOption.objects.filter(
                        property=property_id):
                    temp.append("%s|%s" % (property_id, option.id))
                properties.append(temp)
            else:
                properties.append(["%s|%s" % (property_id, value)])

    # Create a variant for every requested option combination
    for i, options in enumerate(manage_utils.cartesian_product(*properties)):

        if product.has_variant(options):
            continue

        price = request.POST.get("price")

        slug = ""
        for option in options:
            property_id, option_id = option.split("|")
            o = PropertyOption.objects.get(pk=option_id)
            slug += "-" + slugify(o.name)

        slug = "%s%s" % (product.slug, slug)
        sku = "%s-%s" % (product.sku, i + 1)

        variant = Product(slug=slug,
                          sku=sku,
                          parent=product,
                          price=price,
                          variant_position=i + 1,
                          sub_type=VARIANT)
        variant.save()

        # Save the value for this product and property
        for option in options:
            property_id, option_id = option.split("|")
            pvo = ProductPropertyValue(product=variant,
                                       property_id=property_id,
                                       value=option_id)
            pvo.save()

    from lfs.manage.views.product.product import selectable_products_inline
    result = simplejson.dumps({
        "properties":
        manage_variants(request, product_id, as_string=True),
    })

    return HttpResponse(result)