Ejemplo n.º 1
0
 def is_changed(self):
     head = Item.objects(item_id=self.head).first()
     if not head:
         return True
     if self.modify != head.modified:
         return True
     return False
Ejemplo n.º 2
0
def get_spec_info(sku):
    """

    :param sku:
    :return:
    """
    spec = ItemSpec.objects(sku=sku).first()
    if not spec:
        return {'sku': sku, 'found': False}
    item = Item.objects(item_id=spec.item_id).first()
    brand = Brand.objects(en=item.brand).first()
    brand_json = brand and brand.to_json() or ''
    return {
        'sku': sku,
        'found': True,
        'item_id': spec.item_id,
        'title': item.title,
        'brand': brand_json,
        'primary_image': item.primary_img,
        'item_available': item.availability,
        'price': spec.price,
        'available': spec.availability,
        'attributes': spec.attributes,
        'images': spec.images,
        'can_not_return': item.extra.get('can_return') is False,
    }
Ejemplo n.º 3
0
    def items(self):
        """

        :return:
        """
        items_range = request.headers.get('Range', '0-24')
        start, end = items_range.split('-')

        query = restruct_query(request.args)
        try:
            items = Item.objects(**query).order_by('-created_at')
        except:
            pass

        try:
            items_size = items.count()
        except:
            items_size = len(items)

        data = items[int(start):int(end)]
        data = [to_json(item) for item in data]
        resp = make_response(json_util.dumps(data), 200)
        resp.headers['Range-Unit'] = 'items'
        resp.headers['Content-Range'] = '%s-%s/%s' % (start, end, items_size)
        resp.headers['Content_Type'] = 'application/json'
        return resp
Ejemplo n.º 4
0
    def __init__(self,
                 entries_info,
                 user=None,
                 logistic_provider=None,
                 address=None):
        entries = []
        for info in entries_info:
            spec = ItemSpec.objects(sku=info['sku'].first())
            if not spec or not spec.availability:
                continue

            item = Item.objects(item_id=info['item_id']).first()
            if not item or not item.availability:
                continue

            entry = FakeEntry(spec=spec, item=item, quantity=info['quantity'])
            entries.append(entry)
        for entry in entries:
            entry.update_amount()

        self.entries = entries
        self.customer = user
        self.logistic_provider = logistic_provider
        self.address = address
        self.coupon_codes = []
        self.coin = 0
        self.cash = 0
        self.id = 'fakecart'
Ejemplo n.º 5
0
 def update_to_head(self):
     head = Item.objects(item_id=self.head).first()
     if head:
         data = head._data
         for k, v in data.items():
             setattr(self, k, v)
         self.save()
     else:
         return self
Ejemplo n.º 6
0
def get_items_weight(item_ids):
    """

    :param item_ids:
    :return:
    """
    total = 0
    for item_id, quantity in item_ids:
        item = Item.objects(item_id=item_id).first()
        if not item:
            continue
        total += item.weight * quantity

    return total
Ejemplo n.º 7
0
def update_item_availability(item_id):
    """

    :param item_id:
    :return:
    """
    item = Item.objects(item_id=item_id, availability=True).first()
    if not item:
        return None
    for spec in item.specs:
        if spec.availability:
            return

    item.update(set__availability=False, set__status='DEL')
Ejemplo n.º 8
0
def board_json(board):
    """

    :param board:
    :return:
    """
    return dict(
        id=str(board.id),
        date=str(board.published_at),
        image=board.image,
        desc=board.description,
        title=board.title,
        items=[item_json_in_list(item) for item in Item.objects(web_id__in=board.items[: 8])]
    )
Ejemplo n.º 9
0
    def create_from_skus(cls,
                         customer_id,
                         skus,
                         logistic_provider,
                         coupon_codes,
                         coin=0,
                         cash=0,
                         address=None,
                         **kwargs):
        entries = []
        for s in skus:
            availability = check_availability_and_update_stock(
                s['item_id'], s['sku'], s['quantity'])
            if not availability:
                return s
            spec = ItemSpec.objects(sku=s['sku']).first()
            item = Item.objects(item_id=['item_id']).first()
            entry = OrderEntry(spec=spec, item=item,
                               quantity=s['quantity']).save()
            entries.append(entry)

        order = cls(customer_id=customer_id,
                    entries=entries,
                    logistic_provider=logistic_provider,
                    coupon_codes=coupon_codes,
                    coin=coin,
                    cash=cash,
                    **kwargs)
        if not order.forex:
            order.forex = ForexRate.get()

        order.update_amount()
        order.reload()
        # 简介
        for e in order.entries:
            e.create_snapshot()

        if address:
            order.set_address(address)

        order_created.send('system', order=order)
        return order
Ejemplo n.º 10
0
    def update(self):
        """

        :return:
        """
        query = request.get_json()
        data = {}
        for k, v in query['meta'].items():
            if v in [None, 'None', '', 'null']:
                continue
            if type(v) == dict:
                continue
            elif 'price' in k:
                val = float(v)
            elif k == 'weight':
                val = float(v)
            elif k == 'primary_img':
                path = '{}/{}.jpg'.format('other', uuid4())
                val = jobs.image.upload('maybe-img',
                                        path,
                                        url=v,
                                        make_thumbnails=True)
            else:
                val = v
            data.update({k: val})
        data.update({
            'discount':
            ceil(((data['original_price'] - data['price']) /
                  data['original_price']) * 100)
        })
        data.update({'meta': data})
        try:
            item = Item.objects(web_id=data['web_id']).first()
            item.modify(data, data['price'])
            return jsonify(message='OK')
        except Exception as e:
            return jsonify(message='Failed', desc=e)
Ejemplo n.º 11
0
def import_items(ls):
    """

    :param ls:
    :return:
    """
    translator = MSTranslate('maybe', '')
    for row in ls:
        f = row.split('\t')
        url = f[0]
        title = f[1]
        title_en = translator.translate(title, 'en', 'zh')
        china_price = float(float(f[2] + float(f[3])))
        price = float(str(china_price / 6.3).split('.')[0] + '.99')
        origin_price = float(str(price * 1.2).split('.')[0] + '.99')
        weight = float(f[4])
        attributes = f[8].replace('{', '').replace('}', '').split(':')
        vendor = 'taobao'
        brand = 'other'
        main_category = 'home'
        sub_category = 'storage box'
        primary_img = f[9].replace(', ', ',').split(',')
        description = f[10]
        ps = parse.urlparse(url)
        web_id = parse.parse_qs(ps.query)['id'][0]

        images = []
        for img in primary_img:
            path = '{}/{}.jpeg'.format(brand, uuid4())
            url = upload('maybe-img', path, url=img, make_thumbnails=True)
            images.append(url)

        item = Item.objects(web_id=web_id).first()
        if item:
            web_sku = 'taobao:%s' % primary_img[0].split('/')[-2]
            ItemSpec(
                **{
                    'item_id': item.item_id,
                    'web_sku': web_sku,
                    'images': images,
                    'original_price': origin_price,
                    'price': price,
                    'attribute': {
                        attributes[0]: attributes[1]
                    }
                }).save()
            continue

        data = {
            'meta': {
                'url': url,
                'web_id': web_id,
                'title': title,
                'title_en': title_en,
                'china_price': china_price,
                'original_price': origin_price,
                'main_category': main_category,
                'sub_category': sub_category,
                'price': price,
                'weight': weight,
                'attributes': [attributes[0]],
                'vendor': vendor,
                'brand': brand,
                'primary_img': primary_img[0],
                'description': description,
                'currency': 'USD',
                'sex_tag': 'UNCLASSIFIED',
                'tags': []
            },
            'specs': [{
                'web_sku': 'taobao: %s' % primary_img[0].split('/')[-2],
                'image': images,
                'original_price': origin_price,
                'price': price,
                'attribute': {
                    attributes[0]: attributes[1]
                }
            }],
        }
        Item.create(data)
Ejemplo n.º 12
0
    def add_item(self):
        """

        :return:
        """
        query = request.get_json()
        data = {}
        for k, v in query.items():
            if v in [None, 'None', '', 'null']:
                continue
            elif 'price' in k:
                val = float(v)
            elif k == 'primary_img':
                path = '{}/{}.jpg'.format('other', uuid4())
                val = jobs.image.upload('maybe-img',
                                        path,
                                        url=v,
                                        make_thumbnails=True)
            else:
                val = v
            data.update({k: val})
        try:
            china_price = data['china_price'] + data.pop('express_price')
            cost_price = COST_PRICE(china_price, data['weight'])
            price = CURRENT_PRICE(cost_price)
            origin_price = ORIGIN_PRICE(price)
            vendor = 'taobao'
            brand = 'other'
            main_category = 'home'
            sub_category = 'unclassified'
            ps = parse.urlparse(data['url'])
            web_id = parse.parse_qs(ps.query)['id'][0]
            translator = MSTranslate('maybe', '')
            title_en = translator.translate(data['title'], 'en', 'zh')

            data.update({
                'web_id':
                web_id,
                'title_en':
                title_en,
                'china_price':
                china_price,
                'original_price':
                origin_price,
                'price':
                price,
                'main_category':
                main_category,
                'sub_category':
                sub_category,
                'creator':
                current_user.name,
                'vendor':
                vendor,
                'brand':
                brand,
                'availability':
                False,
                'currency':
                'USD',
                'sex_tag':
                'UNCLASSIFIED',
                'tags': [],
                'discount':
                ceil(((origin_price - price) / origin_price) * 100),
            })

            attr_data = {}
            for attr in data['attributes']:
                attr_data.update({attr: None})

            spec_data = {
                'web_sku': str(time.time()).replace('.', ''),
                'images': [data['primary_img']],
                'china_price': china_price,
                'original_price': origin_price,
                'price': price,
                'attributes': attr_data,
            }
            data = {'meta': data, 'spec': [spec_data]}
            item = Item.create(data)
            return jsonify(message='OK', item=item)
        except Exception as e:
            return jsonify(message='OK', desc=e)