示例#1
0
    def __init__(self, user, comparatorId=None):

        req = GenericObject()
        req.user = user

        # New comparator
        if ("%s" % comparatorId).strip().lower() == "new":
            try:
                comparatorId = Order.objects.filter(
                    buyer=user,
                    state=-1,
                    cart_name="comparator",
                    comparator_id__lt=0
                ).order_by("comparator_id")[0].comparator_id - 1
            except IndexError:
                comparatorId = -1
        elif not mongo_db.grids.find_one({
            "user" : user.pk,
            "comparatorId" : comparatorId,
        }):
            raise Grid.DoesNotExist("The requested grid does not exist!")

        self.user = user
        self.comparatorId = comparatorId # NOTE: This also initializes the Mongo object if it doesn't exist yet
        self.cart = Cart().getCart(req, "comparator", comparatorId)
示例#2
0
def results(request):
    def get_queryset(f):
        r = Product.objects
        r = r.filter(ingestion_date__gte=f['min_ingestion_date'],
                     ingestion_date__lte=f['max_ingestion_date'],
                     satellite__startswith=f['satellite']
                     )

        if f['orbit_direction']:
            r = r.filter(orbit_direction__in=f['orbit_direction'])

        if f['polarisation_mode']:
            r = r.filter(polarisation_mode__contains=f['polarisation_mode'])

        if f['product_type']:
            r = r.filter(product_type__in=f['product_type'])

        if f['sensor_mode']:
            r = r.filter(mode__in=f['sensor_mode'])

        if f['relative_orbit_number'] is not None:
            r = r.filter(relative_orbit_number=f['relative_orbit_number'])

        if f['search_extent_min_x'] is not None:
            search_extent = Polygon.from_bbox((f['search_extent_min_x'],
                                               f['search_extent_min_y'],
                                               f['search_extent_max_x'],
                                               f['search_extent_max_y'])
                                              )

            r = r.filter(coordinates__intersects=search_extent)

        r_geom = []
        for result in r:
            r_tuple = result.coordinates.tuple[0]
            r_tuple_coords = []
            for point in r_tuple:
                r_tuple_coords.append([point[1], point[0]])
            r_geom.append("L.polygon("
                          + str(r_tuple_coords)
                          + ", {className: '"
                          + result.id
                          + "', color: '#000', "
                            "weight: '1', "
                            "fillOpacity: '0.1'"
                            "}).addTo(map);"
                          )
        return r, r_geom

    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data

            search_extent_js = None

            if form_data['search_extent_min_x'] is not None:
                search_extent = Polygon.from_bbox((form_data['search_extent_min_x'],
                                                   form_data['search_extent_min_y'],
                                                   form_data['search_extent_max_x'],
                                                   form_data['search_extent_max_y'])
                                                  )

                search_extent_js = 'L.geoJSON(' \
                                   + search_extent.geojson \
                                   + ', {style: ' \
                                     '{"color": "#000", ' \
                                     '"weight": 1, ' \
                                     '"fillOpacity": 0, ' \
                                     '"dashArray": "10, 5"}' \
                                     '}).addTo(map);'

                cart = Cart(request)
                cart.set_extent(search_extent.geojson)

            results, results_geom = get_queryset(form_data)
            return render(request, 'search/results.html',
                          context={'form': form.cleaned_data,
                                   'results': results,
                                   'results_geom': results_geom,
                                   'search_extent': search_extent_js})
        else:
            return redirect('search_form')
示例#3
0
class Grid(object):

    user = None
    cart = None
    attrs = {
        "comparatorId" : None,      # Unique index for the grid and its corresponding comparator orders
        "name" : "Unsaved Grid",    # A friendly name the user gives the grid
        "base_og" : None,           # The base order guide the grid is built on
        "vendors" : [],             # A list of vendor pks used in the grid
        "groups" : [],              # An iterable list of the groups the tags are broken into (called "sections" for users)
        "tag_order" : {},           # A dict containing the group followed by an iterable list of its tags
        "tag_enabled" : {},         # A dict containing a boolean for each tag as to whether it is enabled for this grid
        "priority_items" : {},      # Dict: vendor : { 'tag' : listing_pk } containing the item to use for a tag for a vendor
        "par_levels" : {},          # A dict containing just the tag as key and the par level as the value
        "delivery_type" : -1,       # An int containing the delivery type to be used -- if anything other than [0, 1, 2] all delivery types are shown
        "saved" : False,            # Whether or not the grid has been "saved"
    }

    def __init__(self, user, comparatorId=None):

        req = GenericObject()
        req.user = user

        # New comparator
        if ("%s" % comparatorId).strip().lower() == "new":
            try:
                comparatorId = Order.objects.filter(
                    buyer=user,
                    state=-1,
                    cart_name="comparator",
                    comparator_id__lt=0
                ).order_by("comparator_id")[0].comparator_id - 1
            except IndexError:
                comparatorId = -1
        elif not mongo_db.grids.find_one({
            "user" : user.pk,
            "comparatorId" : comparatorId,
        }):
            raise Grid.DoesNotExist("The requested grid does not exist!")

        self.user = user
        self.comparatorId = comparatorId # NOTE: This also initializes the Mongo object if it doesn't exist yet
        self.cart = Cart().getCart(req, "comparator", comparatorId)

    def __getattr__(self, name):
        if name in self.attrs.keys():
            value = self.mongo.get(name, self.attrs.get(name, None))
            if type(value) == dict:
                try:
                    new_val = { base64.decodestring(k):v for k, v in value.items() }
                    value = new_val
                except Exception as e:
                    pass
            return value
        return super(Grid, self).__getattribute__(name)

    def __setattr__(self, name, value):
        if name in self.attrs.keys() and name != "comparatorId":
            if type(value) == dict:
                # Keys MUST be encoded because certain chars are reserved for Mongo keys (partiularly ".")
                value = { base64.urlsafe_b64encode(k):v for k, v in value.items() }
            return mongo_db.grids.update(
                {
                    "user" : self.user.pk,
                    "comparatorId" : self.comparatorId,
                },
                { "$set" : { name : value } },
                True # Create if not exists
            )
        super(Grid, self).__setattr__(name, value)

    def delete(self, soft=False):
        Order.objects.filter(
            buyer = self.user.pk,
            state = -1,
            cart_name = "comparator",
            comparator_id = self.comparatorId
        ).delete()
        if not soft:
            return mongo_db.grids.delete({
                "user" : self.user.pk,
                "comparatorId" : self.comparatorId,
            })
        else:
            self.normalize_orders()
        return True

    def save(self):
        self.saved = True

    @property
    def catalog(self):
        """
        A cheap way to get all the grids for the user who owns this grid
        """
        grids = mongo_db.grids.find({"user" : self.user.pk})
        g_dict = {}
        try:
            while True:
                grid = grids.next()
                if not grid.get('saved'):
                    continue
                g_dict[grid['comparatorId']] = grid['name']
        except Exception as e:
            pass
        return g_dict

    @property
    def mongo(self):
        m = mongo_db.grids.find_one({
            "user" : self.user.pk,
            "comparatorId" : self.comparatorId,
        })
        if not m:
            m = {
                "user"          : self.user.pk,
                "comparatorId"  : self.comparatorId,
                "name"          : "Unsaved Grid",
                "saved"         : False,
            }
            mongo_db.grids.ensure_index(
                [("user", 1), ("comparatorId", 1)],
                unique=True,
                drop_dups=True
            )
            mongo_db.grids.insert(m)
        return m

    @property
    def vendor_objs(self):
        d = cache.get("grid_vendor_objs_%s_%s" % (self.user.pk, self.comparatorId))
        if not d:
            d = OrderedDict()
            for v_pk in self.vendors:
                v = Vendor.objects.get(pk=v_pk)
                d[v_pk] = v
            self.normalize_orders()
            cache.set(
                "grid_vendor_objs_%s_%s" % (self.user.pk, self.comparatorId),
                d,
                1
            )
        return d

    def normalize_orders(self):

        # No need to run this more than once a second
        if not cache.add("grid_normalize_%s_%s" % (self.user.pk, self.comparatorId), True, 1):
            return

        for v_pk in self.vendors:
            order, created = Order.objects.get_or_create(
                buyer = self.user,
                vendor = Vendor.objects.get(pk=v_pk),
                cart_name = "comparator",
                comparator_id = self.comparatorId,
                state = -1
            )
            if created:
                order.save()

        Order.objects.filter(
            buyer = self.user,
            cart_name = "comparator",
            comparator_id = self.comparatorId,
            state = -1,
        ).exclude(
            vendor__pk__in = self.vendors,
        ).delete()

    @property
    def orders(self):
        orders_dict = cache.get("grid_orders_%s_%s" % (self.user.pk, self.comparatorId))
        if not orders_dict:
            self.normalize_orders()
            orders_dict = {}
            orders = Order.objects.filter(
                buyer = self.user,
                cart_name = "comparator",
                comparator_id = self.comparatorId,
                state = -1,
            )
            for o in orders:
                orders_dict[o.vendor.pk] = o
            cache.set(
                "grid_orders_%s_%s" % (self.user.pk, self.comparatorId),
                orders_dict,
                1
            )
        return orders_dict

    @property
    def vendors_by_tag(self):

        d = cache.get("grid_vendors_by_tag_%s_%s" % (self.user.pk, self.comparatorId))
        if not d:

            d = OrderedDict()

            l_quantities = {}
            self.normalize_orders()
            for o in self.cart.cart_orders():
                for e in o.entry_set.all():
                    l_quantities[e.listing.pk] = l_quantities.get(e.listing.pk, 0) + (float(e.quantity) / float(e.qty_multiplier))

            buyer = self.user.userprofile.buyer
            og_pks = buyer.orderguide_listing_pks
            for group, tags in self.tag_order.items():
                for tag in tags:
                    if not tag or tag == "UNTAGGED":
                        continue
                    d[tag] = OrderedDict()
                    for v_pk in self.vendors:
                        d[tag][v_pk] = []
                    items = mongo_db.orderguide_tags.find({
                        'user' : self.user.pk,
                        'listing' : { '$in' : og_pks },
                        'tag' : tag,
                    }).distinct("listing")
                    items = Listing.objects.filter(
                        pk__in=items,
                        vendor__pk__in=self.vendors,
                    )
                    for l in items:
                        l.ser = l.serialize(buyer=buyer)
                        l.cur_qty = int(l_quantities.get(l.pk, 0))
                        if (
                            self.priority_items
                            and type(self.priority_items) == dict
                            and self.priority_items.get("%s" % l.vendor.pk, {}).get(tag,"") == ("%s" % l.pk)
                        ):
                            d[tag][l.vendor.pk].insert(0, l)
                        else:
                            d[tag][l.vendor.pk].append(l)
            cache.set(
                "grid_vendors_by_tag_%s_%s" % (self.user.pk, self.comparatorId),
                d,
                1
            )
        return d

    class DoesNotExist(Exception):

        def __init__(self, msg=""):
            if ("%s" % msg).strip() == "":
                msg = "Unspecified Exception"
            self.msg = msg

        def __str__(self):
            return self.msg
示例#4
0
def cart(request):
    return {'cart': Cart(request)}