Esempio n. 1
0
def new_order(request):
    logger.info("Receiving new order from woocommerce...")
    data = json.loads(request.body.decode())
    o = data["order"]
    logger.info(" -> order is: %s - %s (%s)", o["order_number"], o["order_key"], o["created_at"])
    try:
        with transaction.atomic():
            order, created = C2OOrder.objects.get_or_create(store_platform = 'woo', store_order_id = o["order_key"])
            if created:
                logger.info("found new order with woo key id '%s', saving...", o["order_key"])
                order.luma_id = C2OOrder.get_new_luma_id()
                order.notes = blank_if_none(o.get('note', ''))
                cust = o['customer']
                addr = o.get("shipping_address", {})
                order.customer_name	= cust['first_name'] + " " + cust['last_name']
                order.customer_email = cust.get("email", "")
                order.customer_telephone =  o['customer'].get("billing_address", {}).get("phone", "")
                order.address_delivery_name	= addr['first_name'] + " " + addr['last_name']
                order.address_company_name = addr.get('company', '')
                order.address_address_line_1 = blank_if_none(addr.get('address_1', ''))
                order.address_address_line_2 = blank_if_none(addr.get('address_2', ''))
                order.address_city = blank_if_none(addr.get('city', ''))
                order.address_county = blank_if_none(addr.get('state', ''))
                order.address_postcode = blank_if_none(addr.get('postcode', ''))
                country = pycountry.countries.get(alpha2=addr.get('country', ''))
                order.address_country = country.name
                order.save()
                link = settings.HOST + '/orders/new_c2o_orders/'
                for item in o['line_items']:
                    product = safe_get(C2OProduct.objects.filter(woo_variants__sku = item['sku']))
                    if not product:
                        logger.warning("Can't find a WooCommerce product for %s, title: '%s' - listing_id: '%s'" % (order, item['name'], item['sku']))
                        send_admin_email("Order #%s - product missing!" % order.luma_id, "Can't find a WooCommerce product for order #%s, title: '%s' - listing_id: '%s'" % (order.luma_id, item['name'], item['sku']))
                        continue
                    size_info = safe_get(list(filter(lambda m: m['key'] == 'pa_size', item['meta'])))
                    if not size_info:
                        raise Exception("Can't find size meta in WooCommerce order item! (%s - %s)" % (item['name'], item['sku']))
                    size = size_info['value']
                    C2OOrderItem.objects.create(order = order,
                                                product_id = product.unique_id,
                                                size = convert_to_c2o_size(size),
                                                quantity = item['quantity'])
                send_admin_email("New order from WooCommerce", "Your new WooCommerce order can be found here: %s" % link)
            else:
                logger.warning("order with woo key '%s' already exists!", o["order_key"])
                send_admin_email("Order duplicated from WooCommerce", "Order with woo key '%s' already exists!" % o["order_key"])
    except:
        logger.error(get_exception_trace())
        return HttpResponseServerError()
    return HttpResponse("ok!")
Esempio n. 2
0
 def validate(self, check_for_send = False):
     product = self.get_product()
     if not product:
         raise OrderValidationException("Can't find product '%s'" % self.product_id)
     if not self.quantity:
         raise OrderValidationException("Empty quantity for %s" % self)
     if not self.size:
         raise OrderValidationException("Empty size for %s" % self)
     sku = safe_get(C2OSku.objects.filter(name = product.sku_name, colour = product.colour, size = self.size))
     if not sku:
         raise OrderValidationException("Can't find sku '%s-%s-%s'" % (product.sku_name, product.colour, self.size))
     self.c2o_sku = sku.sku_code
     self.save()
Esempio n. 3
0
def check_for_new_etsy_orders():
    logger.info("searching etsy orders with status 'open'...")
    etsy = EtsyAPI(settings.ETSY_SHOP_ID, settings.ETSY_CLIENT_KEY, settings.ETSY_CLIENT_SECRET, settings.ETSY_RESOURCE_OWNER_KEY, settings.ETSY_RESOURCE_OWNER_SECRET)
    countries = etsy.get_countries()
    orders = etsy.get_new_orders()
    for o in orders:
        receipt_id = o['receipt_id']
        country = list(filter(lambda c: c['country_id'] == o['country_id'], countries))[0]
        with transaction.atomic():
            order, created = C2OOrder.objects.get_or_create(store_platform = 'etsy', store_order_id = receipt_id)
            if created:
                logger.info("found new order with etsy id '%s', saving...", receipt_id)
                order.luma_id = C2OOrder.get_new_luma_id()
                order.notes = blank_if_none(o.get('message_from_buyer', ''))
                order.customer_name	= o['name']
                order.customer_email = o['buyer_email']
                order.customer_telephone = ''
                order.address_delivery_name	= o['name']
                order.address_company_name = ''
                order.address_address_line_1 = blank_if_none(o.get('first_line', ''))
                order.address_address_line_2 = blank_if_none(o.get('second_line', ''))
                order.address_city = blank_if_none(o.get('city', ''))
                order.address_county = blank_if_none(o.get('state', ''))
                order.address_postcode = blank_if_none(o.get('zip', ''))
                order.address_country = country['name']
                order.save()
                link = settings.HOST + '/orders/new_c2o_orders/'
                for item in etsy.get_order_items(receipt_id):
                    product = safe_get(C2OProduct.objects.filter(etsy_listing_id = item['listing_id']))
                    if not product:
                        logger.warning("Can't find an Etsy product for %s, title: '%s' - listing_id: '%s'" % (order, item['title'], item['listing_id']))
                        send_admin_email("Order #%s - product missing!" % order.luma_id, "Can't find an Etsy product for order #%s, title: '%s' - listing_id: '%s'" % (order.luma_id, item['title'], item['listing_id']))
                        continue
                    C2OOrderItem.objects.create(order = order,
                                                product_id = product.unique_id,
                                                size = convert_to_c2o_size(item['size']),
                                                quantity = item['quantity'])
                send_admin_email("New order from Etsy", "Your new Etsy order can be found here: %s" % link)
            else:
                if order.status == C2OOrder.STATUS_NEW:
                    logger.warning("new order with etsy id '%s' already exists!", receipt_id)
                    send_admin_email("New Order duplicated from Etsy", "Order with etsy id '%s' already exists!" % receipt_id)
Esempio n. 4
0
def import_c2o_catalogue(request):
    params = {}
    if request.method == 'POST':
        form = ImportForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded_file_path = handle_uploaded_file(request.FILES['file'])
            csv_reader = get_reader('CSV')()
            csv_reader.parse_doc(open(uploaded_file_path, encoding='utf-8'))
            models.C2OSku.objects.all().delete()
            saved = 0
            num_lines = sum(1 for line in open(uploaded_file_path, encoding='utf-8'))
            for record in csv_reader.iter_doc():
                category = record['Product Category']
                name = record['Product Name']
                if not category in C2O_CATEGORIES:
                    continue
                if not any([substr in name for substr in C2O_NAME_CONTAINS]):
                    continue
                sku = safe_get(models.C2OSku.objects.filter(sku_code = record['SKU']))
                if not sku:
                    sku = models.C2OSku(sku_code = record['SKU'])
                sku.name = record['Product Name']
                sku.category = record['Product Category']
                sku.colour = record['Colour']
                sku.in_stock = int(record['In Stock'])
                sku.size = record['Size']
                sku.save()
                saved += 1
                logger.info("saved sku '%s' (%s) (%s/%s)", sku.name, sku.sku_code, saved, num_lines)
            logger.info("End import, saved %s records out of %s", saved, num_lines)
            params['saved'] = str(saved)
            params['num_lines'] = str(num_lines)
    else:
        form = ImportForm()
    params['form'] = form
    return render(request, "import.html", params)
Esempio n. 5
0
 def get_product(self):
     return safe_get(C2OProduct.objects.filter(unique_id=self.product_id))