Exemplo n.º 1
0
    def sell_order(self, argumentMap):
        # Decode JSON
        data = {}
        try:
            data = json.loads(self.request.body)
        except ValueError:
            return self.abort(400)

        # Check API key
        if not self.checkApiKeyIsAdmin(data.get('api_key')) and not self.checkApiKeyIsAdmin(argumentMap.get('api_key')):
            return self.abort(403)

        # Get order id
        if 'id' not in data:
            return self.abort(400)

        orderId = long(data['id'])

        # Get sell date or set it to now
        if 'date' in data:
            dateSold = datetime.datetime.fromtimestamp(data['date'])
        else:
            dateSold = datetime.datetime.fromtimestamp(time.time())

        # Set order as sold
        entities.apiOrder().setSold(orderId, dateSold)

        self.response.write(json.dumps({ 'success': True }))
Exemplo n.º 2
0
    def sell_order(self, argumentMap):
        # Decode JSON
        data = {}
        try:
            data = json.loads(self.request.body)
        except ValueError:
            return self.abort(400)

        # Check API key
        if not self.checkApiKeyIsAdmin(
                data.get('api_key')) and not self.checkApiKeyIsAdmin(
                    argumentMap.get('api_key')):
            return self.abort(403)

        # Get order id
        if 'id' not in data:
            return self.abort(400)

        orderId = long(data['id'])

        # Get sell date or set it to now
        if 'date' in data:
            dateSold = datetime.datetime.fromtimestamp(data['date'])
        else:
            dateSold = datetime.datetime.fromtimestamp(time.time())

        # Set order as sold
        entities.apiOrder().setSold(orderId, dateSold)

        self.response.write(json.dumps({'success': True}))
Exemplo n.º 3
0
    def remove_order(self, queryStringArguments):
        # Check API key
        if not self.checkApiKeyIsAdmin(queryStringArguments.get('api_key')):
            return self.abort(403)

        # Check parameters
        requiredKeys = ['id']
        if not self.checkRequiredKeys(queryStringArguments, requiredKeys):
            return self.abort(400)

        # Get order id
        orderId = queryStringArguments.pop('id')

        # Delete order
        entities.apiOrder().delete(long(orderId))

        json.dump({'success': True}, self.response)
Exemplo n.º 4
0
    def remove_order(self, queryStringArguments):
        # Check API key
        if not self.checkApiKeyIsAdmin(queryStringArguments.get('api_key')):
            return self.abort(403)

        # Check parameters
        requiredKeys = ['id']
        if not self.checkRequiredKeys(queryStringArguments, requiredKeys):
            return self.abort(400)

        # Get order id
        orderId = queryStringArguments.pop('id')

        # Delete order
        entities.apiOrder().delete(long(orderId))

        json.dump({'success': True}, self.response)
Exemplo n.º 5
0
    def add_order_to_favourites(self, argumentMap):
        # Decode JSON
        data = {}
        try:
            data = json.loads(self.request.body)
        except ValueError:
            return self.abort(400)

        # Check API key
        if argumentMap.get('api_key'):
            apiKey = argumentMap.pop('api_key')
        else:
            apiKey = data.get('api_key')

        if not apiKey:
            return self.abort(403)
        apiUser = entities.apiUser().getApiKey(apiKey)
        if not apiUser:
            return self.abort(403)

        # Get order id
        if 'id' not in data:
            return self.abort(400)

        orderId = long(data['id'])

        # Get the order itself
        order = entities.apiOrder().get(orderId)
        if order == None:
            return self.abort(400)

        # Get the name given to the favourite
        if 'name' not in data:
            return self.abort(400)
        orderName = data['name']

        # If the apiUser is an admin, he can specify another user who the order will be favourite to
        user = data.get('user')
        if apiUser.admin and user:
            entities.apifavoriteOrder().add(order.ingredient, 0,
                                            user.key().name(), orderName)
        else:
            entities.apifavoriteOrder().add(order.ingredient, 0,
                                            apiUser.key().name(), orderName)

        json.dump({'success': True}, self.response)
Exemplo n.º 6
0
    def add_order_to_favourites(self, argumentMap):
        # Decode JSON
        data = {}
        try:
            data = json.loads(self.request.body)
        except ValueError:
            return self.abort(400)

        # Check API key
        if argumentMap.get('api_key'):
            apiKey = argumentMap.pop('api_key')
        else:
            apiKey = data.get('api_key')

        if not apiKey:
            return self.abort(403)
        apiUser = entities.apiUser().getApiKey(apiKey)
        if not apiUser:
            return self.abort(403)

        # Get order id
        if 'id' not in data:
            return self.abort(400)

        orderId = long(data['id'])

        # Get the order itself
        order = entities.apiOrder().get(orderId)
        if order == None:
            return self.abort(400)

        # Get the name given to the favourite
        if 'name' not in data:
            return self.abort(400)
        orderName = data['name']

        # If the apiUser is an admin, he can specify another user who the order will be favourite to
        user = data.get('user')
        if apiUser.admin and user:
            entities.apifavoriteOrder().add(order.ingredient, 0, user.key().name(), orderName)
        else:
            entities.apifavoriteOrder().add(order.ingredient, 0, apiUser.key().name(), orderName)

        json.dump({'success': True}, self.response)
Exemplo n.º 7
0
    def update_order(self, argumentMap):
        # Decode JSON
        orderData = {}
        try:
            orderData = json.loads(self.request.body)
        except ValueError:
            return self.abort(409)

        # Check parameters
        requiredKeys = ['components']
        if not self.checkRequiredKeys(orderData, requiredKeys):
            return self.abort(408)

        orderComponents   = orderData.pop('components')
        orderDateCreation = orderData.pop('dateCreation', time.time())
        orderDateSelling  = orderData.pop('dateSelling', None)
        orderId           = orderData.pop('id', None)
        orderFId          = orderData.pop('fid', None)

        # Check API key
        if argumentMap.get('api_key'):
            orderData['api_key'] = argumentMap.pop('api_key')

        apiUser = None
        if orderData.has_key('api_key'):
            apiUser = entities.apiUser().getApiKey(orderData['api_key'])
            if not apiUser:
                return self.abort(407)
            orderUser = apiUser.key().name()
        else:
            orderUser = None

        # Build components list
        componentsIds = []
        steps = {}
        for compId in orderComponents:
            compQuantity = orderComponents[str(compId)]

            # Fetch component
            component = entities.apiComponent().get(long(compId))
            if component == None:
                return self.abort(406)

            # Fetch step
            if component.Step.key().id() not in steps:
                step = entities.apiStep().get(component.Step.key().id())
                if step == None:
                    return self.abort(405)
                steps[component.Step.key().id()] = step
            else:
                step = steps[component.Step.key().id()]

                # Check number of components for type `one`
                if step.type == "one":
                    return self.abort(402)

            # Decrease component stock
            component.stock -= compQuantity
            component.put()

            for i in range(compQuantity):
                componentsIds.append(long(compId))

        # Favorite Hits
        if orderFId != None:
            favourite = entities.apifavoriteOrder().get(orderFId)
            if not favourite:
                return slef.abort(401)
            favourite.nbVote += 1
            favourite.put()

        # Ajout/Update de l'order
        if orderId != None:
            if not apiUser or not apiUser.admin:
                return self.abort(403)
            order = entities.apiOrder().update(componentsIds, long(orderId), datetime.datetime.fromtimestamp(orderDateSelling), str(orderUser))
            self.response.write(json.dumps({ 'orderId': order.key().id() }))
        else:
            order = entities.apiOrder().add(componentsIds, datetime.datetime.fromtimestamp(orderDateCreation), str(orderUser))
            self.response.write(json.dumps({ 'orderId': order.key().id() }))
Exemplo n.º 8
0
    def get_orders(self, argumentMap):
        # Check API key
        apiKey = argumentMap.get('api_key')
        if not apiKey:
            return self.abort(403)
        apiUser = entities.apiUser().getApiKey(apiKey)
        if not apiUser:
            return self.abort(403)

        if 'filter' in argumentMap and argumentMap['filter'] == 'favourite':
            if 'user' in argumentMap:
                orders = entities.apifavoriteOrder().getUserfavOrder(argumentMap['user'], None)
            else:
                orders = entities.apifavoriteOrder().getTopFav(10)
            json.dump([self.serializableDataFromFavourite(order) for order in orders], self.response)
        elif 'filter' in argumentMap:
            filters = {
                'sold':   lambda: entities.apiOrder().getSoldOrder(None),
                'unsold': lambda: entities.apiOrder().getCurrentOrder(None)
            }
            filter = argumentMap['filter']
            if filter not in filters:
                return self.abort(400)
            else:
                if apiUser.admin:
                    # Fetch all orders
                    orders = [self.serializableDataFromOrder(order) for order in filters[filter]()]
                else:
                    # Fetch only the user's orders
                    orders = [self.serializableDataFromOrder(order) for order in filters[filter]() if order.User and order.User.key() == apiUser.key()]
                json.dump(orders, self.response)

        elif 'user' in argumentMap:
            user = entities.apiUser().get(argumentMap['user'])
            if user == None:
                return self.abort(400)

            if apiUser.admin or apiUser.key() == user.key():
                orders = [self.serializableDataFromOrder(order) for order in entities.apiOrder().getUserOrder(argumentMap['user'], None)]
                json.dump(orders, self.response)
            else:
                return self.abort(403)

        else:
            # All orders of just a specific one
            if 'id' in argumentMap:
                order = entities.apiOrder().get(long(argumentMap['id']))
                if apiUser.admin or (order.User and apiUser.key() == order.User.key()):
                    if order:
                        json.dump(self.serializableDataFromOrder(order), self.response)
                else:
                    return self.abort(403)
            else:
                # Only an admin can list all orders
                if apiUser.admin:
                    orders = entities.apiOrder().getAll(None)
                else:
                    orders = entities.apiOrder().getUserOrder(apiUser.key().name(), None)

                ordersData = []
                for order in orders:
                    ordersData.append(self.serializableDataFromOrder(order))

                json.dump(ordersData, self.response)
Exemplo n.º 9
0
    def update_order(self, argumentMap):
        # Decode JSON
        orderData = {}
        try:
            orderData = json.loads(self.request.body)
        except ValueError:
            return self.abort(409)

        # Check parameters
        requiredKeys = ['components']
        if not self.checkRequiredKeys(orderData, requiredKeys):
            return self.abort(408)

        orderComponents = orderData.pop('components')
        orderDateCreation = orderData.pop('dateCreation', time.time())
        orderDateSelling = orderData.pop('dateSelling', None)
        orderId = orderData.pop('id', None)
        orderFId = orderData.pop('fid', None)

        # Check API key
        if argumentMap.get('api_key'):
            orderData['api_key'] = argumentMap.pop('api_key')

        apiUser = None
        if orderData.has_key('api_key'):
            apiUser = entities.apiUser().getApiKey(orderData['api_key'])
            if not apiUser:
                return self.abort(407)
            orderUser = apiUser.key().name()
        else:
            orderUser = None

        # Build components list
        componentsIds = []
        steps = {}
        for compId in orderComponents:
            compQuantity = orderComponents[str(compId)]

            # Fetch component
            component = entities.apiComponent().get(long(compId))
            if component == None:
                return self.abort(406)

            # Fetch step
            if component.Step.key().id() not in steps:
                step = entities.apiStep().get(component.Step.key().id())
                if step == None:
                    return self.abort(405)
                steps[component.Step.key().id()] = step
            else:
                step = steps[component.Step.key().id()]

                # Check number of components for type `one`
                if step.type == "one":
                    return self.abort(402)

            # Decrease component stock
            component.stock -= compQuantity
            component.put()

            for i in range(compQuantity):
                componentsIds.append(long(compId))

        # Favorite Hits
        if orderFId != None:
            favourite = entities.apifavoriteOrder().get(orderFId)
            if not favourite:
                return slef.abort(401)
            favourite.nbVote += 1
            favourite.put()

        # Ajout/Update de l'order
        if orderId != None:
            if not apiUser or not apiUser.admin:
                return self.abort(403)
            order = entities.apiOrder().update(
                componentsIds, long(orderId),
                datetime.datetime.fromtimestamp(orderDateSelling),
                str(orderUser))
            self.response.write(json.dumps({'orderId': order.key().id()}))
        else:
            order = entities.apiOrder().add(
                componentsIds,
                datetime.datetime.fromtimestamp(orderDateCreation),
                str(orderUser))
            self.response.write(json.dumps({'orderId': order.key().id()}))
Exemplo n.º 10
0
    def get_orders(self, argumentMap):
        # Check API key
        apiKey = argumentMap.get('api_key')
        if not apiKey:
            return self.abort(403)
        apiUser = entities.apiUser().getApiKey(apiKey)
        if not apiUser:
            return self.abort(403)

        if 'filter' in argumentMap and argumentMap['filter'] == 'favourite':
            if 'user' in argumentMap:
                orders = entities.apifavoriteOrder().getUserfavOrder(
                    argumentMap['user'], None)
            else:
                orders = entities.apifavoriteOrder().getTopFav(10)
            json.dump([
                self.serializableDataFromFavourite(order) for order in orders
            ], self.response)
        elif 'filter' in argumentMap:
            filters = {
                'sold': lambda: entities.apiOrder().getSoldOrder(None),
                'unsold': lambda: entities.apiOrder().getCurrentOrder(None)
            }
            filter = argumentMap['filter']
            if filter not in filters:
                return self.abort(400)
            else:
                if apiUser.admin:
                    # Fetch all orders
                    orders = [
                        self.serializableDataFromOrder(order)
                        for order in filters[filter]()
                    ]
                else:
                    # Fetch only the user's orders
                    orders = [
                        self.serializableDataFromOrder(order)
                        for order in filters[filter]()
                        if order.User and order.User.key() == apiUser.key()
                    ]
                json.dump(orders, self.response)

        elif 'user' in argumentMap:
            user = entities.apiUser().get(argumentMap['user'])
            if user == None:
                return self.abort(400)

            if apiUser.admin or apiUser.key() == user.key():
                orders = [
                    self.serializableDataFromOrder(order)
                    for order in entities.apiOrder().getUserOrder(
                        argumentMap['user'], None)
                ]
                json.dump(orders, self.response)
            else:
                return self.abort(403)

        else:
            # All orders of just a specific one
            if 'id' in argumentMap:
                order = entities.apiOrder().get(long(argumentMap['id']))
                if apiUser.admin or (order.User
                                     and apiUser.key() == order.User.key()):
                    if order:
                        json.dump(self.serializableDataFromOrder(order),
                                  self.response)
                else:
                    return self.abort(403)
            else:
                # Only an admin can list all orders
                if apiUser.admin:
                    orders = entities.apiOrder().getAll(None)
                else:
                    orders = entities.apiOrder().getUserOrder(
                        apiUser.key().name(), None)

                ordersData = []
                for order in orders:
                    ordersData.append(self.serializableDataFromOrder(order))

                json.dump(ordersData, self.response)