예제 #1
0
    def export_depotitem_inventory(modeladmin, request, queryset):
        response, writer = write_csv("DepotItems")
        writer.writerow([
            "ID", "sku", "渠道别名sku", "实际库存量", "已锁库存量", "可用库存量", "库位", "成本",
            "单位成本"
        ])
        queryset = queryset.filter(qty__gt=0)
        for query in queryset:
            order_alias_list = order.models.Alias.objects.filter(
                channel_id=1, item_id=query.item.id, deleted=False).first()
            sku_alias = u""
            if order_alias_list:
                sku_alias = order_alias_list.sku

            canuse_qty = query.qty - query.qty_locked
            row = [
                str(query.id),
                eu(query.item.sku),
                str(sku_alias),
                str(query.qty),
                str(query.qty_locked),
                str(canuse_qty),
                eu(query.position),
                str(query.total),
                str(round(query.total / query.qty, 2))
            ]
            writer.writerow(row)
        return response
예제 #2
0
def import_depotitem_location(request):
    data= {}
    if request.POST:
        mag1=''
        if not request.FILES:
            data_error = u'请选择文件后再提交'
            messages.add_message(request, messages.ERROR,u'上传失败:%s'%data_error)
        else:
            depot = request.POST['depot_id']
            datas = request.FILES['csvFile']
            filename = datas.name.split('.')[0]
            csvdata = StringIO.StringIO(datas.read())
            reader = csv.reader(csvdata)

            headers = next(reader)#去掉首行
            for row in reader:
                row = [i.strip() for i in row]
                alias = Alias.objects.filter(deleted=False,sku=row[1]).first()
                #先查询销售别名sku,别名sku不存在则查询货品sku
                if not alias:

                    item = Item.objects.filter(deleted=False,sku=row[1]).first()
                    if item:
                        alias = Alias()
                        alias.item_id = item.id
                if alias:
                    depotitem = DepotItem.objects.filter(item_id=alias.item_id,depot_id=depot).first()
                    if depotitem:
                        if depotitem.position:
                            old_list =depotitem.position.split(',')
                            if row[2] not in old_list:
                                depotitem.position += ','+row[2]
                        else:
                            depotitem.position = row[2]
                        depotitem.save()
                        mag1 += u'SUCCESS,%s,%s |'%(row[1],depotitem.position)
                    else:
                        depotitem = DepotItem.objects.create(item_id=alias.item_id,depot_id=depot,position=row[2])
                        mag1 += u'SUCCESS,%s,%s |'%(row[1],depotitem.position)

                else:

                    mag1 += u'ERROR,%s,%s,alias not exist |'%(row[1],row[2])

            if mag1:
                #下载表格,错误提示
                response, writer = write_csv("import_depotitem_location_errors")
                writer.writerow(['库位导入信息反馈'])
                datas = mag1.split('|')
                for pd in datas:
                    writer.writerow([pd])
                return response

    return TemplateResponse(request,'import_depotitem_location.html',{'data':data})
예제 #3
0
    def export_itemwanted(modeladmin, request, queryset):
        # Create the HttpResponse object with the appropriate CSV header.
        # response = HttpResponse(content_type='text/csv')
        # response.write('\xEF\xBB\xBF')
        # response['Content-Disposition'] = 'attachment; filename="DepotItem.csv"'
        response, writer = write_csv("itemwanted")
        writer.writerow([
            "ID", "包裹单", "包裹单货品", "订单", "采购单号", "仓库", "SKU", "渠道sku销售别名",
            "Item size", "供应商", "供应商类型", "采购需求数量", "新增时间", "修改时间", "是否已删除"
        ])
        for query in queryset:
            order_alias = order.models.Alias.objects.filter(
                channel_id=1, item_id=query.item.id, deleted=False).first()
            sku_alias = u""
            if order_alias:
                sku_alias = order_alias.sku

            size_id = query.item.key.split("-")[2]
            product_option = Option.objects.filter(id=size_id,
                                                   deleted=False).first()
            if product_option:
                size = product_option.name
            else:
                size = u''

            if not query.purchaseorderitem:
                supplier_name = ""
                supplier_type = ""
                purchaseorder_id = ""
            else:
                supplier_name = query.purchaseorderitem.purchaseorder.supplier.name
                supplier_type = query.purchaseorderitem.purchaseorder.supplier.get_type_display(
                )
                purchaseorder_id = query.purchaseorderitem.purchaseorder_id

            row = [
                str(query.id),
                str(query.package_item.package.id),
                str(query.package_item.id),
                str(query.package_item.package.order.id),
                str(purchaseorder_id),
                str(query.depot.name),
                str(query.item.sku),
                str(sku_alias),
                str(size),
                str(supplier_name),
                str(supplier_type),
                str(query.qty),
                str(query.created),
                str(query.updated),
                str(query.deleted)
            ]
            writer.writerow(row)
        return response
예제 #4
0
def handle(request):
    data = {}

    if request.POST.get('type') == 'orderitem_detail':

        try:
            from_time = eparse(request.POST.get('from'), offset=" 00:00:00+08:00")
            to_time = eparse(request.POST.get('to'), offset=" 00:00:00+08:00") or get_now()
        except Exception, e:
            messages.error(request, u'请输入正确的时间格式')
            return redirect('order_handle')
        shop = request.POST.get('shop')
        channel_id = request.POST.get('channel')

        response, writer = write_csv("order_cost")
        orderitem_detail(writer, from_time, to_time, shop, channel_id)
        return response
예제 #5
0
    def export_depotitem(modeladmin, request, queryset):
        # Create the HttpResponse object with the appropriate CSV header.
        # response = HttpResponse(content_type='text/csv')
        # response.write('\xEF\xBB\xBF')
        # response['Content-Disposition'] = 'attachment; filename="DepotItem.csv"'
        response, writer = write_csv("DepotItem")
        writer.writerow([
            "ID", "sku", "渠道别名sku", "实际库存量", "已锁库存量", "可用库存量", "库位", "成本",
            "单位成本"
        ])
        for query in queryset:
            order_alias = order.models.Alias.objects.filter(
                channel_id=1, item_id=query.item.id, deleted=False).first()
            sku_alias = u""
            if order_alias:
                sku_alias = order_alias.sku

            canuse_qty = query.qty - query.qty_locked
            if query.qty:
                row = [
                    str(query.id),
                    eu(query.item.sku),
                    str(sku_alias),
                    str(query.qty),
                    str(query.qty_locked),
                    str(canuse_qty),
                    eu(query.position),
                    str(query.total),
                    str(round(query.total / query.qty, 2))
                ]
            else:
                row = [
                    str(query.id),
                    eu(query.item.sku),
                    str(sku_alias),
                    str(query.qty),
                    str(query.qty_locked),
                    str(canuse_qty),
                    eu(query.position),
                    str(query.total), 0
                ]
            writer.writerow(row)
        return response
예제 #6
0
def export_upload_format(request):
    """包裹上传格式导出"""
    msg = ""
    # 对输入的package_id 进行去重复
    package_ids_r = request.POST.get('package_id', '').strip().split("\r\n")
    package_ids = list(set(package_ids_r))
    package_ids.sort(key=package_ids_r.index)

    if request.POST.get("type") == "eub_format_export":
        response, writer = write_csv("eub_format_export")
        writer.writerow([
            "订单号", "商品交易号", "商品SKU", "数量", "收件人姓名(英文)", "收件人地址1(英文)",
            "收件人地址2(英文)", "收件人地址3(英文)", "收件人城市", "收件人州", "收件人邮编", "收件人国家",
            "收件人电话", "收件人电子邮箱"
        ])

        for package_id in package_ids:
            package_items = PackageItem.objects.filter(
                package__status=3).filter(package_id=package_id)
            if not package_items:
                msg += u"%s对应的Package或status不是打包中, 或不存在或没有package产品\n" % package_id
                continue

            package = Package.objects.get(id=package_id)
            package.set_to_logistics()
            for pi in package_items:
                row = [
                    package.id,
                    '',
                    pi.item.sku,
                    pi.qty,
                    eu(package.name),
                    eu(package.address),
                    "",
                    "",
                    eu(package.shipping_city),
                    eu(package.shipping_state),
                    eu(package.shipping_zipcode),
                    eu(package.shipping_country.name),
                    format_shipping_phone(package.shipping_phone),
                    eu(package.email),
                ]
                writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response
    elif request.POST.get("type") == "sku_list":
        response, writer = write_csv("sku_list")
        writer.writerow(
            ["SKU编号", "商品中文名称", "商品英文名称", "重量(3位小数)", "报关价格(整数)", "原寄地"])

        skus = PackageItem.objects.filter(package__status=3)\
                                  .filter(package_id__in=package_ids)\
                                  .values_list('item__sku', flat=True)\
                                  .distinct()
        for sku in skus:
            item = Item.objects.get(sku=sku)
            row = [
                sku,
                eu(item.category.cn_name),
                eu(item.category.name),
                item.weigth or item.product.weight,
                10,
                'CN',
            ]
            writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response

    elif request.POST.get("type") == "chukouyi_export":
        response, writer = write_csv("chukouyi_export")
        writer.writerow([
            '库存编码', '客户备注Custom', 'Remark', 'Tracking Number', 'Declared Name',
            'Declared Value(USD)', 'Quantity', 'Weight', 'Packing', 'Name',
            'Address Line1', 'Address Line2', 'Town/City', 'State/Province',
            'Zip/Postal Code', 'Country', 'Phone Number', 'Email'
        ])

        for package_id in package_ids:
            try:
                package = Package.objects.get(id=package_id)
            except Exception, e:
                msg += u"| package_id为 %s 不存在" % package_id
                continue
            packageitem = package.set_to_logistics()
            row = [
                '',
                '`' + str(package.id),
                '',
                '',
                packageitem.item.product.category.name,
                '10.00',
                '1',
                package.weight * 1000,
                '1*1*1',
                eu(package.name),
                eu(package.shipping_address),
                eu(package.shipping_address1),
                eu(package.shipping_city),
                eu(package.shipping_state),
                '`' + eu(package.shipping_zipcode),
                package.shipping_country.name,
                '`' + eu(package.shipping_phone),
                eu(package.email),
            ]
            writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response
예제 #7
0
def shouji(request):
    """收寄导出"""
    msg = ""
    package_ids = request.POST.get('package_id', '').strip().split("\r\n")

    if request.POST.get("type") == "nxb_pickup_export":
        response, writer = write_csv("nxb_pickup_export")
        writer.writerow([
            "邮件号码", "寄达局名称", "邮件重量", "单件重量", "寄达局邮编", "英文国家名", "英文州名", "英文城市名",
            "收件人姓名", "收件人地址", "收件人电话", "寄件人姓名(英文)", "寄件人省名(英文)", "寄件人城市名(英文)",
            "寄件人地址(英文)", "寄件人电话", "内件类型代码", "内件名称", "内件英文名称", "内件数量", "单价",
            "产地"
        ])

        for package_id in package_ids:
            p_3bao = Package3bao.objects.filter(package__status=5)\
                                        .filter(package__shipping__label='NXB')\
                                        .filter(package_id=package_id)\
                                        .first()
            if not p_3bao:
                msg += u"%s对应的Package或status不是已发货, 或不是NXB, 或不存在\n" % package_id
                continue

            package = p_3bao.package
            p_item = package.set_to_logistics()

            row = [
                eu(package.tracking_no),
                eu(package.shipping_country.cn_name),
                str(package.weight * 1000) + 'g',
                str(round(package.weight / package.qty, 3) * 1000) + 'g',
                '`' + package.shipping_zipcode,
                eu(package.shipping_country.name),
                eu(package.shipping_state),
                eu(package.shipping_city),
                eu(package.name),
                eu(package.address),
                format_shipping_phone(package.shipping_phone),
                "Wang Jian",
                "Nanjing",
                "Nanjing",
                "No.63 Longtan Logistics Park,Qixia District",
                "`442032899993",
                "1",
                eu(p_item.cn_name).replace('&', ' '),
                eu(p_item.name).replace('&', ' '),
                package.qty,
                "10",
                "cn",
            ]
            writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response
    elif request.POST.get("type") == "eub_pickup_export":
        response, writer = write_csv("eub_pickup_export")
        writer.writerow(["运单号", "订单号", "内件数", "客户代码", "客户姓名", "电话", "邮箱"])

        for package_id in package_ids:
            package = Package.objects.filter(id=package_id)\
                                     .filter(shipping__label='EUB')\
                                     .filter(status=5)\
                                     .first()
            if not package:
                msg += u"%s对应的Package或status不是已发货, 或不是EUB, 或不存在\n" % package_id
                continue

            package.set_to_logistics()

            row = [
                eu(package.tracking_no),
                package.id,
                package.qty,
                "C04",
                package.name,
                format_shipping_phone(package.shipping_phone),
                eu(package.email),
            ]
            writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response
    elif request.POST.get("type") == "eub_weight_pickup_export":
        response, writer = write_csv("eub_weight_pickup_export")
        writer.writerow(["邮件号", "收件人国家", "重量"])

        for package_id in package_ids:
            package = Package.objects.filter(id=package_id)\
                                     .filter(shipping__label='EUB')\
                                     .filter(status=5)\
                                     .first()
            if not package:
                msg += u"%s对应的Package或status不是已发货, 或不是EUB, 或不存在\n" % package_id
                continue

            row = [
                eu(package.tracking_no),
                package.shipping_country.code,
                package.get_weight(),
            ]
            writer.writerow(row)
        if msg:
            messages.error(request, msg)
        else:
            return response

    return redirect('tongguan_index')
예제 #8
0
def k_tongguan(request):
    msg = ''
    if request.POST.get("type") == "tongguan_k_tongguan":
        carrier_style_codes = {
            "NXB": '3201985002',
            "EUB": '3201981289',
            "FEDEX": '3202382511',
        }
        response, writer = write_csv("k_tong_guan_order")
        writer.writerow([
            '原始订单编号',
            '进出口标志',
            '物流企业代码',
            '物流企业运单号',
            '订单商品货款',
            '订单商品运费',
            '订单税款总额',
            '收货人名称',
            '收货人地址',
            '收货人电话',
            '收货人所在国家',
            '企业商品货号',
            '商品数量',
            '计量单位',
            '币制代码',
            '商品总价',
            '新sku',
            'ws_sku',
        ])
        package_ids = request.POST['package_ids'].strip().split('\r\n')
        carrier = request.POST.get('carrier', '').upper()
        for package_id in package_ids:
            package = Package.objects.filter(id=package_id).first()
            print package
            if not package:
                msg += u"Package:%s is not exist.|" % package_id
                continue

            order = package.order

            if package.status == 4:
                msg += u"Package:%s is not canceled.|" % package_id
                continue

            tongguan_info = order.cannot_tongguan()
            if tongguan_info:
                msg += u"Package:%s %s.|" % (package_id, tongguan_info)
                continue

            package_carrier = package.shipping and package.shipping.label.strip(
            ).upper()
            if package_carrier != carrier:
                msg += u'!!这条单号的物流不是%s,是%s,请注意维护!!|' % (carrier,
                                                        package_carrier)
                continue

            carrier_code = carrier_style_codes.get(carrier,
                                                   u"!!物流单号为空, 请注意维护!!")

            #金额分摊
            rate = order.rate if order.rate != 0 else 1
            order_amount = round(order.amount / rate, 2)
            order_amount_shipping = round(order.amount_shipping / rate, 2)

            # 将订单金额和orderitem的产品金额之差进行均摊, 如果产品金额为0, 则改为0.1
            # 表格的最小单位, 是packageitem, 但是相同model的packageitem需要进行合并
            # 解决思路, 制作一个model: price的dict

            order_items = OrderItem.objects.filter(order_id=order.id)\
                                           .exclude(qty=0)\
                                           .filter(deleted=False)\
                                           .values_list('item__product__sku', 'price', 'qty')

            # 因为要根据model进行合并, 因此认为相同model的金额是一样的, 并且取这个order中同model的最大price
            model_price = {}
            for model, price, qty in order_items:
                price = round((price or 0.1) / rate, 2)

                if model not in model_price:
                    model_price[model] = {
                        'price': price,
                        'qty': qty,
                    }
                else:
                    if model_price[model]['price'] < price:
                        model_price[model]['price'] = price
                    model_price[model]['qty'] += qty

            # 计算新的model下, order的产品金额
            order_product_amount = 0
            for model, data in model_price.iteritems():
                order_product_amount += data['price'] * data['qty']

            amount_delta = order_amount - order_product_amount

            # 将差值进行按比例均摊, 得出最终产品应该的价格
            finnal_model_price = {}
            for model, data in model_price.iteritems():
                finnal_model_price[model] = round(
                    (data['price'] / order_product_amount) * amount_delta +
                    data['price'], 2)

            package_items = PackageItem.objects.filter(
                package=package).values_list('item__product__sku', 'qty')
            package_amount = 0
            package_models = {}
            for model, qty in package_items:
                model_amount = finnal_model_price[model] * qty
                if model not in package_models:
                    package_models[model] = {
                        'qty': qty,
                        'amount': model_amount,
                    }
                else:
                    package_models[model]['qty'] += qty
                    package_models[model]['amount'] += model_amount
                package_amount += model_amount

            for p_model, data in package_models.iteritems():
                p_3bao = Product3bao.objects.filter(sku=p_model).first()
                if not p_3bao:
                    unit_str = ''
                    choies_model = ''  # to delete暂时先使用旧的已备案model, 等新的sku备案完成, 再使用新的product的sku

                else:
                    choies_model = p_3bao.get_choies_model()  # to delete

                    unit_str = p_3bao.unit.split('/')
                    if unit_str:
                        unit_str = unit_str[0]
                    else:
                        unit_str = ''

                # 最后两列展示新的sku和旧的sku
                ws_alias = Alias.objects.filter(
                    item__product__sku=p_model).first()
                if not ws_alias:
                    ws_sku = "这个是全新的产品"
                else:
                    ws_sku = ws_alias.sku

                row = [
                    package.id,
                    'E',
                    eu(carrier_code),
                    package.tracking_no,
                    round(package_amount, 2),
                    '0',
                    '0',
                    eu(package.get_name()),
                    eu(package.get_address()),
                    '`' + eu(package.shipping_phone),
                    package.shipping_country.number,
                    choies_model,  # todo 新sku备案好后,更新为新的sku
                    data['qty'],
                    '`' + unit_str,
                    '502',
                    round(data['amount'], 2),
                    p_model,
                    ws_sku,
                ]
                writer.writerow(row)

        if msg:
            errors = msg.split('|')
            for err in errors:
                writer.writerow([eu(err)])

        return response
    elif request.POST.get("type") == "tongguan_export_product":
        # 如果产品没有3bao信息, 则在表格最后展示新, 旧sku
        response, writer = write_csv("tongguan_product")
        skus = request.POST['skus'].strip().split('\r\n')
        write_3bao_info(skus, writer)
        return response

    elif request.POST.get("type") == 'export_not_record_skus':
        response, writer = write_csv("not_record_skus")
        used_skus = set(
            OrderItem.objects.filter(order__channel__type=2).values_list(
                'item__product__sku', flat=True).distinct())
        recorded_skus = set(
            Product3bao.objects.filter(status=1).values_list('sku', flat=True))
        no_record_skus = list(used_skus - recorded_skus)

        product3bao_no_record = Product3bao.objects.filter(
            status=0).values_list('sku', flat=True)
        no_record_skus2 = list(
            set(product3bao_no_record) - set(no_record_skus))[:3000]
        no_record_skus.extend(no_record_skus2)
        write_3bao_info(no_record_skus, writer)

        return response
    else:
        return redirect('tongguan_index')
예제 #9
0
                continue

            if not package3bao.is_tonanjing:
                msg += u"上传的第%s行的package_id: %s 对应的三宝package的发往南京状态为0 |" % (
                    i, res['package_id'])
                continue

            package3bao.is_over = is_over
            package3bao.save()

        if msg:
            messages.error(request, msg)
        else:
            messages.success(request, u'海关审结状态更新成功')
    elif request.POST.get("type") == 'export_package3bao':
        response, writer = write_csv("package3bao")
        writer.writerow([
            'Package_id',
            'Ordernum',
            'Shipping',
            'tracking_no',
            'print_time',
            'is_tonanjing',
            'is_over',
            'remark',
        ])

        try:
            from_time = eparse(request.POST.get('from'),
                               offset=" 00:00:00+08:00")
            to_time = eparse(request.POST.get('to'),
예제 #10
0
def export_depotitem_cost_inventory(request):
    data= {}
    if request.POST:
        msg1 = msg2 =''
        if request.POST.get("type") == 'export_depotitem_cost_inventory':
            item_str = request.POST.get("item")
            if not item_str:
                msg1 += u"请输入货品sku"
                messages.add_message(request, messages.ERROR,u'查询失败:%s'%msg1)
            else:
                item_array = item_str.strip().split('\r\n')

                i =0
                data ={}
                for item_sku in item_array:
                    i +=1
                    item_sku = item_sku.strip()
                    item = Item.objects.filter(deleted=False,sku=item_sku).first()

                    if not item:
                        item_alias = Alias.objects.filter(deleted=False,sku=item_sku,channel=1).first()
                        if not item_alias:
                            msg2 += u"%s货品sku和choies别名sku在系统里不存在 |"% item_sku
                        else:
                            item = Item.objects.filter(deleted=False,id=item_alias.item_id).first()
                            data[i] = item
                    else:
                        data[i] = item

                if not msg1 and not msg2:
                    #下载产品相关的成本库存数据
                    response, writer = write_csv("export_depotitem_cost_inventory")
                    writer.writerow([
                        'Item_sku', 'chioes_model','chioes_sku', 'model', 'supplier_name','南京仓实际库存',
                        '南京仓已锁库存', '产品参考成本','货品参考成本', 'item实际成本=仓库货品总成本/数量',
                    ])

                    for j in data:
                        depotitem = DepotItem.objects.filter(deleted=False,item_id=data[j].id,depot__code=1).first()
                        supplier = SupplierProduct.objects.filter(deleted=False,product_id=data[j].product.id).order_by('order').values_list('supplier__name', flat=True)
                        supplier_str = ','.join(supplier)
                        alias = Alias.objects.filter(deleted=False,item_id=data[j].id,channel=1).values_list('sku', flat=True)
                        sku_str = ','.join(alias)
                        if depotitem:
                            if depotitem.qty:
                                real_cost = depotitem.total/depotitem.qty
                            else:
                                real_cost=0
                            row = [
                                data[j].sku,
                                data[j].product.choies_sku,
                                sku_str,
                                data[j].product.sku,
                                eu(supplier_str),
                                depotitem.qty,
                                depotitem.qty_locked,
                                data[j].product.cost,
                                data[j].cost,
                                real_cost,
                            ]
                        else:
                            row = [
                                data[j].sku,
                                data[j].product.choies_sku,
                                sku_str,
                                data[j].product.sku,
                                eu(supplier_str),
                            ]
                        writer.writerow(row)
                    return response

                elif msg2:
                    #下载表格,错误提示
                    response, writer = write_csv("export_depotitem_cost_inventory_error")
                    writer.writerow(['error item_sku'])
                    data_array = msg2.split('|')
                    for p in data_array:
                        writer.writerow([p])
                    return response
    return TemplateResponse(request,'export_depotitem_cost_inventory.html',{'data':data})
예제 #11
0
        response, writer = write_csv("order_cost")
        orderitem_detail(writer, from_time, to_time, shop, channel_id)
        return response

    elif request.POST.get("type") == 'order_cost':
        try:
            from_time = eparse(request.POST.get('from'), offset=" 00:00:00+08:00")
            to_time = eparse(request.POST.get('to'), offset=" 00:00:00+08:00") or get_now()
        except Exception, e:
            messages.error(request, u'请输入正确的时间格式%s' % str(e))
            return redirect('order_handle')

        shop = request.POST.get('shop')
        channel_id = request.POST.get('channel')

        response, writer = write_csv("order_cost")
        order_cost(writer, from_time, to_time, shop, channel_id)
        return response

    elif request.POST.get('type') == 'manual_import_order':
        msg = ''
        reader = csv.reader(StringIO.StringIO(request.FILES['csvFile'].read()))
        try:
            channel = Channel.objects.get(id=request.POST.get('channel'))
        except Exception, e:
            messages.error(request, u"请选择正确的渠道账号")
            return redirect('order_handle')

        # 使用速卖通模板
        if channel.type == 2:
            header = next(reader)
예제 #12
0
def import_buyer_product(request):

    data_notice = {}
    if request.POST:
        data_error = ''
        data = {}
        if not request.FILES:
            data_error = u'请选择文件后再提交'
            messages.add_message(request, messages.ERROR, data_error)
        else:
            datas = request.FILES['csvFile']
            filename = datas.name.split('.')[0]
            csvdata = StringIO.StringIO(datas.read())
            reader = csv.reader(csvdata)

            headers = next(reader)  #去掉首行

            std_header1 = [
                '产品分类', '产品中文名称', '颜色', '尺码', '产品净重', '尺码描述', '材质', '供应商ID',
                '供应商名称', '供应商货号', '择尚拿货价', '供应商提供的参考库存', '快递费用', '[备注]',
                '[是否有弹性(0:否,1:是)]', '[拉链(0:无,1:前拉链,2:侧,3后)]',
                '[是否透明(0:否,1:是)]', '[配件说明]'
            ]
            std_header = [
                '\xef\xbb\xbf产品分类', '产品中文名称', '颜色', '尺码', '产品净重', '尺码描述', '材质',
                '供应商ID', '供应商名称', '供应商货号', '择尚拿货价', '供应商提供的参考库存', '快递费用',
                '[备注]', '[是否有弹性(0:否,1:是)]', '[拉链(0:无,1:前拉链,2:侧,3后)]',
                '[是否透明(0:否,1:是)]', '[配件说明]'
            ]
            field_header = [
                'category',
                'cn_name',
                'color',
                'size',
                'weight',
                'description',
                'material',
                'supplier_ID',
                'supplier_name',
                'supplier_sku',
                'supplier_cost',
                'supplier_inventory',
                'shipping_fee',
                'note',
                'note1',
                'note2',
                'note3',
                'note4',
            ]

            # for i in range(1,18):
            #     # print i
            #     if std_header[i] != headers[i]:
            #         data_error +=u',%s表格与范本不一致,可能是没有另外为utf-8'
            if headers != std_header and headers != std_header1:
                data_error += u"表格与范本不一致,可能是没有另存为utf-8 |"
            else:
                j = 0
                for row in reader:
                    j += 1
                    row = [i.strip() for i in row]
                    res = dict(zip(field_header, row))
                    for key in res.keys():
                        if key in ['supplier_ID', 'supplier_inventory']:
                            try:
                                res[key] = int(res[key])
                            except Exception, e:
                                res[key] = 0

                        if key in ['weight', 'supplier_cost', 'shipping_fee']:
                            try:
                                res[key] = float(res[key])
                            except Exception, e:
                                res[key] = 0
                        if key == 'size':
                            res['size'] = res['size'].upper()
                        if key in ['category', 'color']:
                            res[key] = res[key].capitalize()
                    #验证供应商id
                    supplier = Supplier.objects.filter(
                        deleted=False, id=res['supplier_ID']).first()
                    if not supplier:
                        data_error += u'第%d行的%s供应商id系统不存在 |' % (
                            j + 1, res['supplier_ID'])
                    #验证分类和属性
                    cate = Category.objects.get(deleted=False,
                                                name=res['category'])
                    try:
                        if res['color']:
                            # attr = cate.attributes.filter(attribute_id=11).values_list('attribute_id', flat=True)
                            option = Option.objects.filter(
                                deleted=False,
                                attribute_id=11,
                                name=res['color']).first()
                            if not option:
                                data_error += u'第%d行的%s颜色系统不存在 |' % (
                                    j + 1, res['color'])

                        if res['size']:
                            diff_size = []
                            table_size = list(set(res['size'].split('#')))
                            attr = cate.attributes.filter(
                                id=cate.id).values_list('id', flat=True)

                            option2 = Option.objects.filter(
                                deleted=False,
                                attribute_id__in=attr).values_list('name',
                                                                   flat=True)
                            diff_size = list(
                                set(table_size).difference(set(option2)))
                            diff_size_str = ','.join(diff_size)
                            if diff_size:
                                data_error += u'第%d行的%s尺码系统不存在 |' % (
                                    j + 1, diff_size_str)
                    except Category.DoesNotExist:
                        data_error += u'第%d行的%s产品分类名称系统不存在 |' % (
                            j + 1, res['category'])
                    data[j] = res

                #验证结束
            if data_error:
                # messages.add_message(request, messages.ERROR, data_error)
                #下载表格,错误提示
                response, writer = write_csv("import_buyer_product_error")
                writer.writerow(['error notice'])
                data_array = data_error.split('|')
                for p in data_array:
                    writer.writerow([p])
                return response
            else:
                # print data
                # 插入数据
                add_user_id = request.user.id
                for table_p in data:
                    category = Category.objects.get(
                        deleted=False, name=data[table_p]['category'])
                    note_str = '[备注]==' + data[table_p][
                        'note'] + '\n[是否有弹性(0:否,1:是)]==      ' + data[table_p][
                            'note1'] + '\n[拉链(0:无,1:前拉链,2:侧,3后)]==      ' + data[
                                table_p][
                                    'note2'] + '\n[是否透明(0:否,1:是)]==      ' + data[
                                        table_p][
                                            'note3'] + '\n[配件说明]==      ' + data[
                                                table_p]['note4']
                    p = Product.objects.create(
                        category_id=category.id,
                        cn_name=data[table_p]['cn_name'],
                        cost=data[table_p]['supplier_cost'],
                        manager_id=category.manager_id,
                        material=data[table_p]['material'],
                        description=data[table_p]['description'],
                        note=note_str,
                        weight=data[table_p]['weight'],
                        adder_id=add_user_id)
                    #新增供应商产品
                    supplier = Supplier.objects.get(
                        deleted=False, id=data[table_p]['supplier_ID'])
                    SupplierProduct.objects.create(
                        supplier=supplier,
                        product=p,
                        supplier_cost=data[table_p]['supplier_cost'],
                        supplier_sku=data[table_p]['supplier_sku'],
                        supplier_inventory=data[table_p]['supplier_inventory'],
                        supplier_shipping_fee=data[table_p]['shipping_fee'])

                    sizes = data[table_p]['size'].split('#')
                    for attribute in category.attributes.filter(
                            deleted=False).order_by('-sort'):
                        product_attribute, is_created = ProductAttribute.objects.get_or_create(
                            attribute_id=attribute.id, product_id=p.id)
                        if product_attribute.attribute_id == 11:
                            if data[table_p]['color']:
                                option_color = Option.objects.get(
                                    name=data[table_p]['color'],
                                    attribute_id=product_attribute.attribute_id
                                )
                                product_attribute.options.add(option_color)
                                if not data[table_p]['size']:  #尺码为空的item
                                    item_str = str(p.id) + str(option_color.id)
                                    item_sku = u"%s-%s" % (p.sku,
                                                           option_color.name)
                                    item, is_created = Item.objects.get_or_create(
                                        product_id=p.id,
                                        key=item_str,
                                        sku=item_sku)
                        else:
                            for op in sizes:
                                option = Option.objects.get(
                                    name=op,
                                    attribute_id=product_attribute.attribute_id
                                )
                                product_attribute.options.add(option)
                                if data[table_p]['color']:  #颜色不为空的item
                                    item_str = str(p.id) + '-' + str(
                                        option_color.id) + '-' + str(option.id)
                                    item_sku = u"%s-%s-%s" % (
                                        p.sku, option_color.name, option.name)
                                else:  #颜色为空的item
                                    item_str = str(p.id) + '-0-' + str(
                                        option.id)
                                    item_sku = u"%s-0-%s" % (p.sku,
                                                             option.name)

                                item, is_created = Item.objects.get_or_create(
                                    product_id=p.id,
                                    key=item_str,
                                    sku=item_sku)
                    #如果尺码和颜色都不存在
                    if not data[table_p]['color'] and not data[table_p]['size']:
                        item_str = str(p.id) + '-'
                        item_sku = u"%s-" % p.sku
                        item, is_created = Item.objects.get_or_create(
                            product_id=p.id, key=item_str, sku=item_sku)

                messages.add_message(request, messages.SUCCESS,
                                     u'%s表格中的产品已全部上传:%d' % (filename, j))
예제 #13
0
def import_update_product(request):
    data_notice = {}
    if request.POST:
        if request.POST.get("type") == 'bulk_import_product':
            data_error = ''
            data = {}
            if not request.FILES:
                data_error = u'请选择文件后再提交'
                messages.add_message(request, messages.ERROR, data_error)
            else:
                datas = request.FILES['csvFile']
                filename = datas.name.split('.')[0]
                csvdata = StringIO.StringIO(datas.read())
                reader = csv.reader(csvdata)

                headers = next(reader)  #去掉首行
                std_header1 = [
                    'model', 'size', '库存(各种尺码之和)', '产品名称', '中文名称', 'category',
                    'category中文名称', '供货商名称', '参考成本', 'total', '重量', '链接',
                    'others', 'site_url网站链接', '供应商货号'
                ]
                std_header = [
                    '\xef\xbb\xbfmodel', 'size', '库存(各种尺码之和)', '产品名称', '中文名称',
                    'category', 'category中文名称', '供货商名称', '参考成本', 'total', '重量',
                    '链接', 'others', 'site_url网站链接', '供应商货号'
                ]
                en_herder = [
                    'model', 'size', 'inventory', 'name', 'cn_name',
                    'category', 'category_cn_name', 'supplier_name', 'cost',
                    'total', 'weight', 'supplier_link', 'other', 'site_url',
                    'supplier_sku'
                ]

                if headers != std_header1 and headers != std_header:
                    data_error = u'提交的文件头列表和范本不一致,请确认是否另存为utf-8'
                    print headers, '_________________'
                    print std_header1
                    messages.add_message(request, messages.ERROR, data_error)
                else:

                    re_notice = import_ws_product_detail_notice(reader)  #检查数据
                    if type(re_notice) == str:
                        messages.add_message(request, messages.ERROR,
                                             re_notice)
                    else:
                        insert_re = import_ws_product_detail(
                            re_notice)  #新增产品数据
                        if insert_re:
                            #下载表格,错误提示
                            response, writer = write_csv(
                                "bulk_import_product_error")
                            writer.writerow(['error model'])
                            data_array = insert_re.split('|')
                            for p in data_array:
                                writer.writerow([p])
                            return response
                        else:
                            messages.add_message(request, messages.SUCCESS,
                                                 u"产品导入成功,请再次更新产品完善捆绑供应商")

        elif request.POST.get("type") == 'import_update_product':
            data_error = ''
            msg = ''
            datas_row = {}
            if not request.FILES:
                data_error = u'请选择文件后再提交'
                messages.add_message(request, messages.ERROR, data_error)
            else:
                datas = request.FILES['csvFile']
                filename = datas.name.split('.')[0]
                csvdata = StringIO.StringIO(datas.read())
                reader = csv.reader(csvdata)

                headers = next(reader)  #去掉首行
                std_header1 = [
                    'model', 'size', '库存(各种尺码之和)', '产品名称', '中文名称', 'category',
                    'category中文名称', '供货商名称', '参考成本', 'total', '重量', '链接',
                    'others', 'site_url网站链接', '供应商货号'
                ]
                std_header = [
                    '\xef\xbb\xbfmodel', 'size', '库存(各种尺码之和)', '产品名称', '中文名称',
                    'category', 'category中文名称', '供货商名称', '参考成本', 'total', '重量',
                    '链接', 'others', 'site_url网站链接', '供应商货号'
                ]
                en_herder = [
                    'model', 'size', 'inventory', 'name', 'cn_name',
                    'category', 'category_cn_name', 'supplier_name', 'cost',
                    'total', 'weight', 'supplier_link', 'other', 'site_url',
                    'supplier_sku'
                ]

                if headers != std_header and headers != std_header1:

                    data_error += u"表格与范本不一致,可能是没有另存为utf-8  |"
                    messages.add_message(request, messages.ERROR, data_error)
                else:
                    j = 0
                    for row in reader:
                        j += 1
                        print row
                        model = row[0].strip()
                        erp_model = Product.objects.filter(
                            choies_sku=model).first()
                        if not erp_model:
                            data_error += u"ERROR,%s model号在新系统里不存在,无法更新  |" % model

                        row = [i.strip() for i in row]
                        res = dict(zip(en_herder, row))
                        for key in res.keys():
                            if key in ['cost']:
                                try:
                                    res[key] = float(res[key])
                                except Exception, e:
                                    res[key] = 0
                                # res[key] = res[key] or 0#如果不是数字会报错
                        datas_row[j] = res

                if not data_error:
                    for k in datas_row:
                        # print '777',k
                        # print datas_row[k]
                        erp_model = Product.objects.get(
                            choies_sku=datas_row[k]['model'])
                        erp_model.name = datas_row[k]['name']
                        erp_model.cn_name = datas_row[k]['cn_name']
                        erp_model.cost = datas_row[k]['cost']
                        if not datas_row[k]['supplier_name']:
                            erp_model.choies_supplier_name = datas_row[k][
                                'supplier_name']
                        erp_model.save()
                        if not datas_row[k]['supplier_name']:
                            continue

                        supplier = Supplier.objects.filter(
                            name=datas_row[k]['supplier_name'],
                            deleted=False).first()
                        if supplier:
                            SupplierProduct.objects.filter(
                                product_id=erp_model.id,
                                deleted=False).update(order=10)
                            sp = SupplierProduct.objects.filter(
                                supplier_id=supplier.id,
                                product_id=erp_model.id,
                                deleted=False).first()
                            if sp:
                                sp.supplier_sku = datas_row[k]['supplier_sku']
                                sp.site_url = datas_row[k]['supplier_link']
                                sp.order = 1
                                sp.save()
                            else:
                                SupplierProduct.objects.create(
                                    supplier_id=supplier.id,
                                    product_id=erp_model.id,
                                    supplier_sku=datas_row[k]['supplier_sku'],
                                    site_url=datas_row[k]['supplier_link'],
                                    order=1)

                        else:
                            SupplierProduct.objects.filter(
                                product_id=erp_model.id,
                                deleted=False).update(order=10)
                            supplier_id = Supplier.objects.create(
                                name=datas_row[k]['supplier_name'])
                            SupplierProduct.objects.create(
                                supplier_id=supplier_id.id,
                                product_id=erp_model.id,
                                supplier_sku=datas_row[k]['supplier_sku'],
                                site_url=datas_row[k]['supplier_link'],
                                order=1)
                        # msg +=u"%s 产品和%s 供应商的信息已更新"%(datas_row[k]['model'],datas_row[k]['supplier_name'])
                    messages.add_message(request, messages.SUCCESS,
                                         u"%s 文件里的%s 行产品更新成功" % (filename, j))
                else:
                    # messages.add_message(request, messages.ERROR, data_error)
                    #下载表格,错误提示
                    response, writer = write_csv("import_update_product_error")
                    writer.writerow(['error model'])
                    data_array = data_error.split('|')
                    for p in data_array:
                        writer.writerow([p])
                    return response