예제 #1
0
    def api_get(request):
        #获取业务数据
        cur_page = request.GET.get('page', 1)
        applications = customer_models.CustomerMessage.objects.filter(
            is_deleted=False)
        filters = dict([(db_util.get_filter_key(key, filter2field),
                         db_util.get_filter_value(key, request.GET))
                        for key in request.GET if key.startswith('__f-')])
        username = filters.get('username', '')
        display_name = filters.get('displayName', '')
        status = filters.get('status', '')
        if username:
            filter_users = User.objects.filter(username__icontains=username,
                                               is_active=True)
            filter_users_ids = [filter_user.id for filter_user in filter_users]
            applications = applications.filter(user_id__in=filter_users_ids)
        if display_name:
            filter_users = User.objects.filter(
                first_name__icontains=display_name, is_active=True)
            filter_users_ids = [filter_user.id for filter_user in filter_users]
            applications = applications.filter(user_id__in=filter_users_ids)
        if status:
            filter_accounts = account_models.UserProfile.objects.filter(
                app_status=status)
            filter_users_ids = [
                filter_account.user_id for filter_account in filter_accounts
            ]
            applications = applications.filter(user_id__in=filter_users_ids)

        pageinfo, applications = paginator.paginate(applications, cur_page,
                                                    COUNT_PER_PAGE)
        user_ids = [application.user_id for application in applications]
        application_ids = [application.id for application in applications]
        server_ip_infos = customer_models.CustomerServerIps.objects.filter(
            customer_id__in=application_ids)  #额外的ip数据
        user_infos = User.objects.filter(id__in=user_ids)
        account_infos = account_models.UserProfile.objects.filter(
            user_id__in=user_ids)
        reject_logs = application_models.ApplicationLog.objects.filter(
            user_id__in=user_ids, status=account_models.REJECT)

        #组装数据
        rows = []
        for application in applications:
            cur_user_info = user_infos.get(id=application.user_id)
            cur_account_info = account_infos.get(user_id=application.user_id)
            if cur_account_info.app_status == account_models.REJECT:
                reject_logs = reject_logs.filter(
                    user_id=int(application.user_id))
                last_reason = reject_logs.last().reason
            server_ips = [
                s.name
                for s in server_ip_infos.filter(customer_id=application.id)
            ]  #为毛不把ip存在一张表里。。。
            server_ips.insert(0, application.server_ip)
            rows.append({
                'id':
                application.id,
                'username':
                cur_user_info.username,
                'displayName':
                cur_user_info.first_name,
                'appName':
                u'默认应用',
                'appId':
                application.app_id if application.app_id else u'审核后自动生成',
                'appSecret':
                application.app_secret
                if application.app_secret else u'审核后自动生成',
                'DeveloperName':
                application.name,
                'phone':
                application.mobile_number,
                'email':
                application.email,
                'serverIp':
                server_ips,
                'interfaceUrl':
                application.interface_url,
                'status':
                account_models.APP_STATUS2NAME[cur_account_info.app_status],
                'status_value':
                cur_account_info.app_status,
                'reason':
                u'驳回原因:' + last_reason
                if cur_account_info.app_status == account_models.REJECT else ''
            })
        data = {'rows': rows, 'pagination_info': pageinfo.to_dict()}

        #构造response
        response = create_response(200)
        response.data = data
        return response.get_response()
예제 #2
0
	def api_get(request):
		cur_page = request.GET.get('page', 1)
		businesses = models.Business.objects.all().order_by('-created_at')
		catalog_id2name = dict((str(catalog.id),catalog.name) for catalog in product_catalog_models.ProductCatalog.objects.filter(level=2))
		filters = dict([(db_util.get_filter_key(key, filter2field), db_util.get_filter_value(key, request)) for key in request.GET if key.startswith('__f-')])
		customer_number = filters.get('customer_number','')
		company_name = filters.get('company_name','')
		product_catalog = filters.get('product_catalog','')
		company_type = filters.get('company_type','')
		phone = filters.get('phone','')
		status = filters.get('status','')
		company_location = filters.get('company_location','')
		if customer_number:
			businesses = businesses.filter(customer_number__icontains=customer_number)
		if company_name:
			businesses = businesses.filter(company_name__icontains=company_name)
		if product_catalog:
			filter_catalogs = product_catalog_models.ProductCatalog.objects.filter(level=2, name__icontains=product_catalog)
			filter_catalogs_ids = [str(filter_catalog.id) for filter_catalog in filter_catalogs]
			filter_business_ids = []
			for business in businesses:
				#得到商家的经营类目
				catalog_ids = business.product_catalog_ids.split('_')
				for filter_catalogs_id in filter_catalogs_ids:
					#判断是否类目是在筛选条件之内
					if filter_catalogs_id in catalog_ids:
						filter_business_ids.append(business.id)
			businesses = businesses.filter(id__in=filter_business_ids)
		if company_type:
			businesses = businesses.filter(company_type=int(company_type))
		if phone:
			businesses = businesses.filter(phone__icontains=phone)
		if status:
			businesses = businesses.filter(status=int(status))
		if company_location:
			businesses = businesses.filter(company_location__icontains=company_location)

		pageinfo, businesses = paginator.paginate(businesses, cur_page, COUNT_PER_PAGE, query_string=request.META['QUERY_STRING'])
		rows = []
		for business in businesses:
			catalog_name = []
			product_catalog_ids = business.product_catalog_ids.split('_')
			for product_catalog in product_catalog_ids:
				if catalog_id2name.has_key(product_catalog):#二级分类如果没有被删除
					catalog_name.append(catalog_id2name[product_catalog])
			catalog_name = ';'.join(catalog_name)
			rows.append({
				'id': business.id,
				'customer_number': business.customer_number,
				'company_name': business.company_name,
				'company_location': business.company_location,
				'company_type': models.TYPE2NAME[business.company_type],
				'product_catalogs': catalog_name,
				'contacter': business.contacter,
				'phone': business.phone,
				'status': models.STATUS2NAME[business.status] if business.status != 3 else models.STATUS2NAME[business.status] + '(' + business.reason + ')'
			})
		data = {
			'rows': rows,
			'pagination_info': pageinfo.to_dict()
		}
		response = create_response(200)
		response.data = data
		return response.get_response()
예제 #3
0
	def api_get(request):
		is_for_list = True if request.GET.get('is_for_list') else False
		cur_page = request.GET.get('page', 1)
		try:
			cur_page = int(cur_page)
		except:
			cur_page = 1
		filter_idct = dict([(db_util.get_filter_key(key, filter2field), db_util.get_filter_value(key, request)) for key in request.GET if key.startswith('__f-')])
		order_id = filter_idct.get('order_id','')
		filter_product_name = filter_idct.get('product_name','')
		status = filter_idct.get('status','-1')
		order_create_at_range = filter_idct.get('order_create_at__range','')

		products = product_models.Product.objects.filter(owner_id=request.user.id)
		product_ids = [int(product.id) for product in products]
		product_has_relations = product_models.ProductHasRelationWeapp.objects.filter(product_id__in=product_ids).exclude(weapp_product_id='')
		product_images = product_models.ProductImage.objects.filter(product_id__in=product_ids)
		image_ids = [product_image.image_id for product_image in product_images]
		images = resource_models.Image.objects.filter(id__in=image_ids)

		user_profile = account_models.UserProfile.objects.filter(user_id=request.user.id).first()
		print '>>>>>>>>>>>>>>>>>>>>>>>>>>>', request.user.id
		if user_profile:
			user_profile_id = user_profile.id
			purchase_method = user_profile.purchase_method #采购方式
			account_has_suppliers = account_models.AccountHasSupplier.objects.filter(account_id=user_profile_id)
			# 为了适配新逻辑
			old_account_has_suppliers = account_models.AccountHasSupplier.objects.filter(account_id=-user_profile_id)
		else:
			account_has_suppliers = account_models.AccountHasSupplier.objects.filter(user_id=request.user.id)
			# 为了适配新逻辑
			old_account_has_suppliers = account_models.AccountHasSupplier.objects.filter(user_id=-request.user.id)
		account_has_suppliers = list(account_has_suppliers) + list(old_account_has_suppliers)
		supplier_ids = []
		api_pids = []
		is_search_product_name = False
		for account_has_supplier in account_has_suppliers:
			if str(account_has_supplier.supplier_id) not in supplier_ids:
				if account_has_supplier.supplier_id > 0:
					supplier_ids.append(str(account_has_supplier.supplier_id))
				else:
					supplier_ids.append(str(-account_has_supplier.supplier_id))

		#构造panda数据库内商品id,与云商通内商品id的关系
		product_id2product_weapp_id = {}
		for product_has_relation in product_has_relations:
			weapp_product_ids = product_has_relation.weapp_product_id.split(';')
			for weapp_product_id in weapp_product_ids:
				if not product_id2product_weapp_id.has_key(product_has_relation.product_id):
					product_id2product_weapp_id[product_has_relation.product_id] = [weapp_product_id]
				else:
					product_id2product_weapp_id[product_has_relation.product_id].append(weapp_product_id)

		#构造云商通内商品id,与panda数据库内商品名称与商品图片的关系
		product_weapp_id2info = {}
		for product_id in product_ids:
			image_id = product_images.filter(product_id=product_id).first().image_id
			url = images.get(id=image_id).path
			product_name = products.get(id=product_id).product_name
			if product_id2product_weapp_id.has_key(product_id):
				product_weapp_ids = product_id2product_weapp_id[product_id]
				for product_weapp_id in product_weapp_ids:
					if not product_weapp_id2info.has_key(product_weapp_id):
						product_weapp_id2info[product_weapp_id] = [{
							'product_name': product_name,
							'product_img': url
						}]
					else:
						product_weapp_id2info[product_weapp_id].append({
							'product_name': product_name,
							'product_img': url
						})
		#查找
		filter_params = {}
		if order_id:
			filter_params['order_id'] = order_id
		if filter_product_name:
			is_search_product_name = True
			#如果按照商品名称查询,则传递product_ids参数给接口
			product_ids = [int(product.id) for product in products.filter(product_name__icontains=filter_product_name)]
			for product_id in product_ids:
				if product_id2product_weapp_id.has_key(product_id):
					product_weapp_ids = product_id2product_weapp_id[product_id]
					for product_weapp_id in product_weapp_ids:
						api_pids.append(product_weapp_id)
			api_pids = '_'.join(api_pids)
		if status != '-1':
			filter_params['status'] = status
		if order_create_at_range:
			start_time = order_create_at_range[0]
			end_time = order_create_at_range[1]
			filter_params['start_time'] = start_time
			filter_params['end_time'] = end_time

		supplier_ids = '_'.join(supplier_ids)
		# print('supplier_ids:')
		# print(supplier_ids)
		rows = []
		orders = []
		if supplier_ids != '':
			#请求接口获得数据
			if is_for_list:
				if is_search_product_name:
					if api_pids!= '':
						#按照商品名搜索、传递商品id
						params = {
							'product_ids': api_pids,
							'supplier_ids': supplier_ids,
							'page':cur_page,
							'count_per_page': COUNT_PER_PAGE
						}
					else:
						#如果商品不存在,直接返回空列表
						orders = []
						pageinfo, orders = paginator.paginate(orders, cur_page, COUNT_PER_PAGE)
						pageinfo = pageinfo.to_dict()
						data = {
							'rows': rows,
							'pagination_info': pageinfo
						}
						#构造response
						response = create_response(200)
						response.data = data
						return response.get_response()
				else:
					params = {
						'supplier_ids': supplier_ids,
						'page':cur_page,
						'count_per_page': COUNT_PER_PAGE
					}
				params.update(filter_params)
				res = Resource.use(ZEUS_SERVICE_NAME, EAGLET_CLIENT_ZEUS_HOST).post(
					{
						'resource': 'panda.order_list_by_supplier',
						'data': params
					}
				)
				if res and res['code'] == 200:
					orders = res['data']['orders']
				else:
					print(res)
					response = create_response(500)
					return response.get_response()
				pageinfo = res['data']['pageinfo']
				pageinfo['total_count'] = pageinfo['object_count']
			else:
				if is_search_product_name:
					if api_pids!= '':
						#按照商品名搜索、传递商品id
						params = {'supplier_ids': supplier_ids,'product_ids': api_pids}
					else:
						return rows
				else:
					params = {'supplier_ids': supplier_ids}
				params.update(filter_params)
				res = Resource.use(ZEUS_SERVICE_NAME, EAGLET_CLIENT_ZEUS_HOST).post(
					{
						'resource': 'panda.order_export_by_supplier',
						'data': params
					}
				)
				if res and res['code'] == 200:
					orders = res['data']['orders']
				else:
					print(res)
					response = create_response(500)
					return response.get_response()

			# price【售价】,purchase_price【结算价】,total_price【售价金额】
			for order in orders:
				order_id = order['order_id']
				product_infos = []
				return_product_infos = order['products'] #返回的订单数据,包含了所需要的product信息
				total_weight = 0
				total_purchase_price = 0
				for return_product_info in return_product_infos:
					product_id = str(return_product_info['id'])
					if product_weapp_id2info.has_key(product_id):#只展示关联了商品id的订单
						if return_product_info['model_names']:
							model_names = u'规格:' + '/'.join(return_product_info['model_names'])
						else:
							model_names = ''
						product_infos.append({
							'product_name': product_weapp_id2info[product_id][0]['product_name'],
							'model_names': model_names,
							'product_img': product_weapp_id2info[product_id][0]['product_img'],
							'price': return_product_info['purchase_price'] if purchase_method == 1 else '%.2f' % (return_product_info['total_price']/return_product_info['count']),
							'count': return_product_info['count']
						})
					else:
						if return_product_info['model_names']:
							model_names = u'规格:' + '/'.join(return_product_info['model_names'])
						else:
							model_names = ''
						product_infos.append({
							'product_name': return_product_info['name'],
							'model_names': model_names,
							'product_img': return_product_info['thumbnails_url'],
							'price': return_product_info['purchase_price'] if purchase_method == 1 else '%.2f' % (return_product_info['total_price']/return_product_info['count']),
							'count': return_product_info['count']
						})
					if not is_for_list:
						total_weight += return_product_info['weight']
					if purchase_method == 1: #固定底价类型客户
						total_purchase_price += int(return_product_info['count']) * float(return_product_info['purchase_price'])#计算订单总金额
					else: #扣点类型客户
						total_purchase_price += float(return_product_info['total_price'])

				if is_for_list:
					rows.append({
						'id': len(rows),
						'order_id': order_id,
						'order_create_at': order['created_at'],
						'ship_name': order['ship_name'],
						'total_purchase_price': str('%.2f' % total_purchase_price),
						'status': order_status2text[order['status']],
						'order_status': order['status'],
						'product_infos': json.dumps(product_infos),
						'express_company_name': order['express_company_name'] if order['express_company_name']  in haved_express_company_name else 'qita',
						'express_company_storename': order['express_company_name'],
						'express_number': order['express_number'],
						'leader_name': order['leader_name'],
						'postage': str('%.2f' % order['postage'])
					})
				else:
					rows.append({
						'id': order_id,
						'order_id': order_id,
						'order_create_at': order['created_at'],
						'ship_name': order['ship_name'],
						'total_purchase_price': str('%.2f' % total_purchase_price),
						'total_weight': total_weight,
						'status': order_status2text[order['status']],
						'product_infos': json.dumps(product_infos),
						'express_company_name': order['express_company_name'] if order['express_company_name']  in haved_express_company_name else 'qita',
						'express_company_storename': order['express_company_name'],
						'express_number': order['express_number'],
						'leader_name': order['leader_name'],
						'ship_tel': order['ship_tel'],
						'ship_address': order['ship_address'],
						'ship_area': order['ship_area'],
						'delivery_time': order['delivery_time'],
						'customer_message': order['customer_message']
					})
		else:
			orders = []
			pageinfo, orders = paginator.paginate(orders, cur_page, COUNT_PER_PAGE)
			pageinfo = pageinfo.to_dict()

		if is_for_list:
			data = {
				'rows': rows,
				'pagination_info': pageinfo
			}
			#构造response
			response = create_response(200)
			response.data = data
			return response.get_response()
		else:
			return rows
예제 #4
0
    def api_get(request):
        """

		"""
        is_for_list = True if request.GET.get('is_for_list') else False
        is_first = True if request.GET.get('is_first') else False  #是否需要发接口请求
        cur_page = request.GET.get('page', 1)
        filter_idct = dict([(db_util.get_filter_key(key, filter2field),
                             db_util.get_filter_value(key, request))
                            for key in request.GET if key.startswith('__f-')])
        customer_name = filter_idct.get('customerName', '')
        filter_product_name = filter_idct.get('productName', '')
        from_mall = filter_idct.get('fromMall', '-1')
        order_status = filter_idct.get('orderStatus', '-1')
        # 订单号
        order_id = filter_idct.get('orderId', '')
        order_create_at_range = filter_idct.get('orderCreateAt__range', '')
        if filter_idct:
            is_first = False  #含有查找条件,发送接口请求
        # product_has_relations = product_models.ProductHasRelationWeapp.objects.exclude(weapp_product_id='')
        if from_mall == '-1':
            from_mall = ''
        else:
            weapp_count = product_models.SelfUsernameWeappAccount.objects.filter(
                self_user_name=from_mall).first()
            weapp_count_id = weapp_count.weapp_account_id
            from_mall = weapp_count_id
        if order_status == '-1':
            order_status = ''
        #
        supplier_ids = []
        if customer_name:
            all_sellers = UserProfile.objects.filter(
                role=CUSTOMER, name__icontains=customer_name, is_active=True)
            account_ids = [seller.id for seller in all_sellers]
            # 获取该客户下旧的供货商id获取到
            account_ids += [-seller.id for seller in all_sellers]
            supplier_ids = [
                a.supplier_id for a in AccountHasSupplier.objects.filter(
                    account_id__in=account_ids)
            ]

            # supplier_ids = [a.supplier_id for a in AccountHasSupplier.objects.filter(user_id__in=account_ids)]
            # supplier_ids = old_supplier_ids + supplier_ids
            # print 'WWWWWWWWWWWWWWWWWWWWWWWWWWWWW', supplier_ids
            # 如果根据名字获取不到供应商,就直接返回none
            if not supplier_ids:
                pageinfo = paginator.paginate_by_count(0, 1, 15, '')
                # print pageinfo
                data = {'rows': [], 'pagination_info': pageinfo}

                # 构造response
                response = create_response(200)
                response.data = data
                return response.get_response()
        # if not supplier_ids:
        # 	account_has_suppliers = AccountHasSupplier.objects.all()
        weapp_product_ids = []
        if filter_product_name:
            product_ids = [
                p.id for p in product_models.Product.objects.filter(
                    product_name__icontains=filter_product_name)
            ]
            weapp_product_ids = [
                product.weapp_product_id
                for product in product_models.ProductHasRelationWeapp.objects.
                filter(product_id__in=product_ids)
            ]
            if not weapp_product_ids:
                # 通过商品名字获取不到商品,直接返回None
                pageinfo = paginator.paginate_by_count(0, 1, 15, '')
                data = {'rows': [], 'pagination_info': pageinfo}
                # 构造response
                response = create_response(200)
                response.data = data
                return response.get_response()
        try:
            cur_page = int(cur_page)
        except:
            cur_page = 1
        params = {
            'page': cur_page,
            'from_mall': from_mall,
            'order_status': order_status,
            'supplier_ids': json.dumps(supplier_ids),
            'product_ids': json.dumps(weapp_product_ids),
            'per_count_page': 15,
            'order_id': order_id
        }
        if order_create_at_range:
            params.update({
                'order_create_start': order_create_at_range[0],
                'order_create_end': order_create_at_range[1],
            })
        # print supplier_ids, '+++++++++++++++++++++++++++'
        if not is_first:
            resp = Resource.use(ZEUS_SERVICE_NAME,
                                EAGLET_CLIENT_ZEUS_HOST).post({
                                    'resource': 'panda.order_list',
                                    'data': params
                                })
        else:
            resp = None

        if resp:
            if resp.get('code') == 200:
                # print resp.get('data').get('orders')
                orders = resp.get('data').get('orders')
                rows = []
                for order in orders:
                    if is_for_list:  #运营订单列表展示用
                        weapp_supplier_id = order.get('products')[0].get(
                            'supplier')
                        supplier = AccountHasSupplier.objects.filter(
                            supplier_id=weapp_supplier_id).last()
                        user_profile = None
                        if supplier:
                            user_profile = UserProfile.objects.filter(
                                user_id=supplier.user_id).first()
                        # print supplier.store_name, '------------------------------------------------'
                        # weapp_owner_id = order.get('owner_id')
                        # 规格信息
                        temp_product_name = []
                        product_model_properties = order['products']
                        total_price = 0
                        for product_model in product_model_properties:

                            total_price += product_model.get(
                                'origin_total_price')
                            product_properties = product_model.get(
                                'custom_model_properties')
                            if product_properties:
                                model_info = [
                                    p_model.get('property_value')
                                    for p_model in product_properties
                                    if product_properties
                                ]

                                if model_info:
                                    model_info = u'(' + '/'.join(
                                        model_info) + u')'
                            else:
                                model_info = ''
                            # print type(model_info), type(product_model.get('count', 0)), type(product_model.get('name', ''))
                            temp_product_name.append( product_model.get('name', '') + model_info \
                                 + u',' + str(product_model.get('count', 0)) + u'件' )

                        # model_info = ''
                        # if product_models:
                        # 	model_info = [p_model.get('property_value') for p_model in product_models]
                        # 	if model_info:
                        # 		model_info = u'('+ '/'.join(model_info) + u')'

                        rows.append({
                            'totalPurchasePrice':
                            '%.2f' % total_price,
                            'orderId':
                            order.get('order_id'),
                            'fromMall': [order.get('store_name')],
                            'orderStatus':
                            order_status2text.get(order.get('status')),
                            'productName':
                            '\n'.join(temp_product_name),
                            'customerName':
                            [user_profile.name if user_profile else ''],
                            'postage':
                            '%.2f' % order.get('postage')
                        })
                    else:
                        #导出订单字段
                        rows.append({
                            'order_id':
                            order['order_id'],
                            'express_company_name':
                            order['express_company_name']
                            if order['express_company_name']
                            in haved_express_company_name else 'qita',
                            'express_company_storename':
                            order['express_company_name'],
                            'express_number':
                            order['express_number']
                        })
                # print rows, '------------------------------------------------'
                if is_for_list:
                    pageinfo = paginator.paginate_by_count(
                        resp.get('data').get('count'), int(cur_page), 15, '')
                    data = {'rows': rows, 'pagination_info': pageinfo}
                    # 构造response
                    response = create_response(200)
                    response.data = data
                    return response.get_response()
                else:
                    return rows
        if not resp:
            pageinfo = paginator.paginate_by_count(0, int(cur_page), 15, '')
            data = {'rows': [], 'pagination_info': pageinfo}
            # 构造response
            response = create_response(200)
            response.data = data
            return response.get_response()
예제 #5
0
def getProductData(request, is_export):
    cur_page = request.GET.get('page', 1)
    is_update = request.GET.get('is_update', False)

    filter_dict = dict([(db_util.get_filter_key(key, filter2field),
                         db_util.get_filter_value(key, request))
                        for key in request.GET if key.startswith('__f-')])
    product_name = filter_dict.get('product_name', '')
    catalog_name = filter_dict.get('catalog_name', '')
    product_status_value = filter_dict.get('product_status', '0')

    user_info = UserProfile.objects.filter(user_id=request.user.id)
    if user_info:
        role = user_info[0].role
        if role == YUN_YING:
            products = models.Product.objects.filter(
                is_deleted=False, is_update=True,
                is_refused=False).order_by('-id')
        else:
            products = models.Product.objects.filter(
                owner=request.user, is_deleted=False).order_by('-id')
    else:
        role = YUN_YING
        products = []

    # 查询
    if product_name:
        products = products.filter(product_name__icontains=product_name)
    if is_update:
        products = products.filter(is_update=is_update)
    if catalog_name:
        product_catalogs = catalog_models.ProductCatalog.objects.filter(
            name__icontains=catalog_name)
        father_id2ids = {}
        for product_catalog in catalog_models.ProductCatalog.objects.all():
            if product_catalog.father_id not in father_id2ids:
                father_id2ids[product_catalog.father_id] = [product_catalog.id]
            else:
                father_id2ids[product_catalog.father_id].append(
                    product_catalog.id)
        catalog_ids = []
        for product_catalog in product_catalogs:
            catalog_id = product_catalog.id
            # 查询的是二级分类
            catalog_ids.append(catalog_id)
            catalog_ids.append(product_catalog.father_id)
            # 查询的是一级分类
            if catalog_id in father_id2ids:
                catalog_ids.extend(father_id2ids[catalog_id])
        products = products.filter(catalog_id__in=catalog_ids)
    if int(product_status_value) != 0:
        product_ids = [product.id for product in products]
        sync_weapp_accounts = models.ProductSyncWeappAccount.objects.filter(
            product_id__in=product_ids)
        has_sync_p_ids = set([
            sync_weapp_account.product_id
            for sync_weapp_account in sync_weapp_accounts
        ])

        has_relation_weapps = models.ProductHasRelationWeapp.objects.filter(
            product_id__in=product_ids)
        has_relation_p_ids = set([
            has_relation_weapp.product_id
            for has_relation_weapp in has_relation_weapps
        ])
        if int(product_status_value) == 1:  #已入库
            products = products.filter(id__in=has_sync_p_ids)

        if int(product_status_value) == 2:  #待入库
            products = products.exclude(id__in=has_relation_p_ids)
            products = products.exclude(id__in=has_sync_p_ids)
            products = products.exclude(is_refused=True)

        if int(product_status_value) == 4:  #入库驳回
            products = products.exclude(id__in=has_sync_p_ids)
            all_reject_p_ids = [
                product.id for product in products.filter(is_refused=True)
            ]  #所有驳回状态的id
            all_has_reject_p_ids = [
                reject_log.product_id
                for reject_log in models.ProductRejectLogs.objects.filter(
                    product_id__in=all_reject_p_ids)
            ]  #是入库驳回的商品id
            products = products.filter(id__in=all_has_reject_p_ids)

    if not is_export:
        pageinfo, products = paginator.paginate(
            products, cur_page, 20, query_string=request.META['QUERY_STRING'])

    product_ids = ['%s' % product.id for product in products]
    owner_ids = set([product.owner_id for product in products])
    product_has_relations = models.ProductHasRelationWeapp.objects.filter(
        product_id__in=product_ids).exclude(weapp_product_id='')
    product_images = models.ProductImage.objects.filter(
        product_id__in=product_ids)

    # 从weapp获取商品销量
    if role == YUN_YING:
        id2sales = {}
        resource_images = resource_models.Image.objects.filter(
            user_id__in=owner_ids)
    else:
        id2sales = sales_from_weapp(product_has_relations)
        resource_images = resource_models.Image.objects.filter(
            user_id=request.user.id)

    #获取分类
    product_catalogs = catalog_models.ProductCatalog.objects.all()
    id2product_catalog = {
        product_catalog.id: product_catalog
        for product_catalog in product_catalogs
    }

    # 获取商品图片
    product_id2image_id = {}
    image_id2images = {}
    for product in product_images:
        # product_id2image_id[product.product_id] = product.image_id
        if product.product_id not in product_id2image_id:
            product_id2image_id[product.product_id] = [product.image_id]
        else:
            product_id2image_id[product.product_id].append(product.image_id)

    for image in resource_images:
        image_id2images[image.id] = image.path
    # 更新商品的库存
    relations = models.ProductHasRelationWeapp.objects.filter(
        product_id__in=product_ids)
    product_2_weapp_product = {
        int(relation.weapp_product_id): relation.product_id
        for relation in relations
    }
    # 单规格商品id:更新后的库存(已经入库的)解决下边单品库存不是最新问题(因为通过接口更新了)
    standard_product_to_store = {}
    if role != YUN_YING:
        standard_product_to_store = update_product_store(
            product_2_weapp_product=product_2_weapp_product, products=products)

    # 获取商品是否上线
    weapp_product_ids = product_2_weapp_product.keys()
    product_shelve_on = get_shelve_on_product(
        weapp_product_ids=weapp_product_ids,
        product_2_weapp_product=product_2_weapp_product)

    # 组装数据
    # 获取多规格商品id和结算价,售价的对应数据
    user_id2name = {}
    if role == YUN_YING:
        model_properties = models.ProductModel.objects.filter(
            owner_id__in=owner_ids, is_deleted=False)
        # p_owner_ids = [product.owner_id for product in products]
        user_profiles = UserProfile.objects.filter(user_id__in=owner_ids)
        user_id2name = {
            user_profile.user_id: user_profile.name
            for user_profile in user_profiles
        }
    else:
        model_properties = models.ProductModel.objects.filter(
            owner=request.user, product_id__in=product_ids, is_deleted=False)

    product_id2market_price = {}
    product_id2product_price = {}
    product_id2product_store = {}
    for model_property in model_properties:
        if model_property.product_id not in product_id2market_price:
            product_id2market_price[model_property.product_id] = [
                model_property.market_price
            ]
        else:
            product_id2market_price[model_property.product_id].append(
                model_property.market_price)

        if model_property.product_id not in product_id2product_price:
            product_id2product_price[model_property.product_id] = [
                model_property.price
            ]
        else:
            product_id2product_price[model_property.product_id].append(
                model_property.price)

        if model_property.product_id not in product_id2product_store:
            product_id2product_store[model_property.product_id] = [
                model_property.stocks
            ]
        else:
            product_id2product_store[model_property.product_id].append(
                model_property.stocks)

    rows = []

    #入库状态数据
    has_relation_weapps = models.ProductHasRelationWeapp.objects.filter(
        product_id__in=product_ids)
    has_relation_p_ids = set([
        has_relation_weapp.product_id
        for has_relation_weapp in has_relation_weapps
    ])
    reject_logs = models.ProductRejectLogs.objects.filter(
        product_id__in=product_ids)
    has_reject_p_ids = [reject_log.product_id for reject_log in reject_logs]
    product_id2reject_reasons = {}
    for reject_log in reject_logs:
        if product_id2reject_reasons.has_key(reject_log.product_id):
            product_id2reject_reasons[reject_log.product_id].append({
                'reject_reasons':
                reject_log.reject_reasons,
                'created_at':
                reject_log.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        else:
            product_id2reject_reasons[reject_log.product_id] = [{
                'reject_reasons':
                reject_log.reject_reasons,
                'created_at':
                reject_log.created_at.strftime('%Y-%m-%d %H:%M:%S')
            }]

    for product in products:
        owner_id = product.owner_id
        image_id = -1 if product.id not in product_id2image_id else product_id2image_id[
            product.id][0]
        image_path = '' if image_id not in image_id2images else image_id2images[
            image_id]
        sales = 0 if product.id not in id2sales else id2sales[product.id]
        product_has_model = 0
        #如果是多规格价格显示区间
        if product.id in product_id2market_price and product.has_product_model:
            market_prices = product_id2market_price[product.id]
            market_prices = sorted(market_prices)
            product_has_model = len(market_prices)
            if (market_prices[0] !=
                    market_prices[-1]) and len(market_prices) > 1:
                clear_price = ('%.2f ~ %.2f') % (market_prices[0],
                                                 market_prices[-1])
            else:
                clear_price = '%.2f' % market_prices[0]
        else:
            clear_price = '%.2f' % product.clear_price

        if product.id in product_id2market_price and product.has_product_model:
            product_prices = product_id2product_price[product.id]
            product_prices = sorted(product_prices)
            if (product_prices[0] !=
                    product_prices[-1]) and len(product_prices) > 1:
                product_price = ('%.2f ~ %.2f') % (product_prices[0],
                                                   product_prices[-1])
            else:
                product_price = '%.2f' % product_prices[0]
        else:
            product_price = '%.2f' % product.product_price
        store_short = False
        if product.id in product_id2product_store and product.has_product_model:
            product_stores = product_id2product_store[product.id]
            product_stores = sorted(product_stores)
            if (product_stores[0] !=
                    product_stores[-1]) and len(product_stores) > 1:
                product_store = ('%s ~ %s') % (product_stores[0],
                                               product_stores[-1])
                if product_stores[-1] < 20:
                    store_short = True
            else:
                product_store = '%s' % product_stores[0]
                if product_stores[0] < 20:
                    store_short = True
        else:

            product_store = product.product_store if not standard_product_to_store.get(product.id) \
             else standard_product_to_store.get(product.id)
            if product.product_store < 20:
                store_short = True

        image_paths = []
        if product.id in product_id2image_id:
            image_ids = product_id2image_id[product.id]
            for i_id in image_ids:
                if i_id in image_id2images:
                    image_paths.append(image_id2images[i_id])
        valid_time_from = product.valid_time_from
        valid_time_to = product.valid_time_to
        valid_time = '' if not valid_time_from else ('%s/%s') % (
            valid_time_from.strftime('%Y-%m-%d %H:%M'),
            valid_time_to.strftime('%Y-%m-%d %H:%M'))

        #商品分类
        first_level_name = ''
        second_level_name = ''
        if product.catalog_id in id2product_catalog:
            product_catalog = id2product_catalog[product.catalog_id]
            father_id = product_catalog.father_id
            second_level_name = product_catalog.name
            first_level_name = '' if father_id not in id2product_catalog else id2product_catalog[
                father_id].name

        #入库状态
        product_status_text, product_status_value = get_product_status(
            product, has_relation_p_ids, has_reject_p_ids)

        #入库驳回原因
        reject_reasons = ''
        if product_status_value == 0:  #待入库
            reject_reasons = [{'reject_reasons': u'暂无记录', 'created_at': ''}]
            reject_reasons = json.dumps(
                reject_reasons
            ) if product.id not in product_id2reject_reasons else json.dumps(
                product_id2reject_reasons[product.id])
        elif product_status_value == 3:
            reject_reasons = json.dumps(product_id2reject_reasons[product.id])

        sale_status = ''
        if product.id not in product_shelve_on:
            if product.product_status in sales_status2text:
                sale_status = sales_status2text[product.product_status]
        else:
            sale_status = u'已上架'

        rows.append({
            'id':
            product.id,
            'role':
            role,
            'customer_name':
            '' if owner_id not in user_id2name else user_id2name[owner_id],
            'promotion_title':
            product.promotion_title,
            'clear_price':
            clear_price,
            'product_price':
            product_price,
            'limit_clear_price':
            '%.2f' %
            product.limit_clear_price if product.limit_clear_price > 0 else '',
            'product_weight':
            '%.2f' % product.product_weight,
            'product_name':
            product.product_name,
            'product_store':
            product_store,
            'store_short':
            store_short,
            'image_path':
            image_path,
            'image_paths':
            image_paths if image_paths else '',
            'remark':
            product.remark,
            'product_status':
            product_status_text,
            'product_status_value':
            product_status_value,
            'status':
            sale_status,
            'sales':
            '%s' % sales,
            'has_limit_time':
            valid_time,
            'product_has_model':
            product_has_model,
            'first_level_name':
            first_level_name,
            'second_level_name':
            second_level_name,
            'is_model':
            product.has_product_model,
            'is_update':
            product.is_update,
            'created_at':
            product.created_at.strftime('%Y-%m-%d %H:%M'),
            'reject_reasons':
            reject_reasons
        })
    if is_export:
        return rows
    else:
        return rows, pageinfo
예제 #6
0
def getCustomerData(request, is_export):
    cur_page = request.GET.get('page', 1)
    user_profiles = UserProfile.objects.filter(role=1,
                                               is_active=True)  #role{1:客户}

    filter_idct = dict([(db_util.get_filter_key(key, filter2field),
                         db_util.get_filter_value(key, request))
                        for key in request.GET if key.startswith('__f-')])
    customer_name = filter_idct.get('customer_name', '')
    if customer_name:
        user_profiles = user_profiles.filter(name__icontains=customer_name)

    if not is_export:
        pageinfo, user_profiles = paginator.paginate(
            user_profiles,
            cur_page,
            10,
            query_string=request.META['QUERY_STRING'])

    user_ids = [user_profile.user_id for user_profile in user_profiles]
    products = product_models.Product.objects.filter(
        owner_id__in=user_ids).order_by('-id')
    product_ids = ['%s' % product.id for product in products]
    product_has_relations = product_models.ProductHasRelationWeapp.objects.filter(
        product_id__in=product_ids).exclude(weapp_product_id='')

    user_id2product_id = {}
    for product in products:
        if product.owner_id not in user_id2product_id:
            user_id2product_id[product.owner_id] = [product.id]
        else:
            user_id2product_id[product.owner_id].append(product.id)

    product_id2name = {
        product.id: product.product_name
        for product in products
    }
    #从云商通获取销量
    id2sales = sales_from_weapp(product_has_relations)
    account_ids = [user_profile.id for user_profile in user_profiles]
    account_has_suppliers = AccountHasSupplier.objects.filter(
        account_id__in=account_ids)
    supplier_ids = []
    for account_has_supplier in account_has_suppliers:
        if str(account_has_supplier.supplier_id) not in supplier_ids:
            supplier_ids.append(str(account_has_supplier.supplier_id))

    api_pids = []

    #构造panda数据库内商品id,与云商通内商品id的关系
    product_weapp_id2product_id = {}
    for product_has_relation in product_has_relations:
        weapp_product_ids = product_has_relation.weapp_product_id.split(';')
        for weapp_product_id in weapp_product_ids:
            api_pids.append(weapp_product_id)
            product_weapp_id2product_id[
                weapp_product_id] = product_has_relation.product_id

    product_id2time = {}
    for product_has_relation in product_has_relations:
        product_id = product_has_relation.product_id
        if product_id not in product_id2time:
            product_id2time[product_id] = [
                product_has_relation.created_at.strftime("%Y-%m-%d")
            ]
        else:
            product_id2time[product_id].append(
                product_has_relation.created_at.strftime("%Y-%m-%d"))
    id2orders = {}
    supplier_ids = '_'.join(supplier_ids)
    api_pids = '_'.join(api_pids)
    try:
        params = {'supplier_ids': supplier_ids}
        r = requests.post(ZEUS_HOST + '/panda/order_export_by_supplier/',
                          data=params)
        res = json.loads(r.text)
        if res['code'] == 200:
            orders = res['data']['orders']
            if orders:
                for order in orders:
                    if int(order['status']) in [3, 4, 5]:
                        weapp_id = str(order['products'][0]['id'])
                        if weapp_id in product_weapp_id2product_id:
                            p_id = product_weapp_id2product_id[weapp_id]
                            if p_id not in id2orders:
                                id2orders[p_id] = [order]
                            else:
                                id2orders[p_id].append(order)
        else:
            print(res)
    except Exception, e:
        print(e)
예제 #7
0
    def api_get(request):
        is_for_list = True if request.GET.get(
            'is_for_list') else False  #是列表还是导出
        cur_page = request.GET.get('page', 1)
        accounts = UserProfile.objects.filter(is_active=True).exclude(
            role=MANAGER).order_by('-id')
        catalogs = catalog_models.ProductCatalog.objects.filter(father_id=-1)
        catalog_id2name = dict(
            (catalog.id, catalog.name) for catalog in catalogs)
        filters = dict([(db_util.get_filter_key(key, filter2field),
                         db_util.get_filter_value(key, request))
                        for key in request.GET if key.startswith('__f-')])
        company_name = filters.get('companyName', '')
        username = filters.get('username', '')
        role = filters.get('accountType', '')
        status = filters.get('status', '')
        # customer_from = filters.get('customerFrom','')
        if company_name:
            accounts = accounts.filter(company_name__icontains=company_name)
        if username:
            user_ids = [
                user.id
                for user in User.objects.filter(username__icontains=username)
            ]
            accounts = accounts.filter(user_id__in=user_ids)
        if role:
            accounts = accounts.filter(role=role)
        if status:
            if status == '1':
                accounts = accounts.filter(status=status)
            else:
                accounts = accounts.exclude(status=1)
        # if customer_from: 客户来源暂时渠道没有接口实现,先注释
        # 	print customer_from
        if is_for_list:
            pageinfo, accounts = paginator.paginate(accounts, cur_page,
                                                    COUNT_PER_PAGE)

        user_ids = [account.user_id for account in accounts]
        user_id2username = {
            user.id: user.username
            for user in User.objects.filter(id__in=user_ids)
        }
        rows = []
        date_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        #从渠道接口获得客户来源字段
        company_name2info = {}
        company_names = []
        for account in accounts:
            if account.company_name != '':
                company_names.append(account.company_name)
        company_names = '_'.join(company_names)
        company_name2info = get_info_from_axe(company_names)

        for account in accounts:
            #关闭已过期的账号/开启可以登录的账号
            if account.valid_time_from and account.valid_time_to:
                valid_time_from = account.valid_time_from.strftime(
                    "%Y-%m-%d %H:%M:%S")
                valid_time_to = account.valid_time_to.strftime(
                    "%Y-%m-%d %H:%M:%S")
                if valid_time_from <= date_now and date_now < valid_time_to and account.status != 0:
                    account.status = 1
                    account.save()
                elif date_now >= valid_time_to or date_now <= valid_time_from:
                    account.status = 2
                    account.save()

            customerFrom = '--'
            if account.role == 1:
                catalog_names = []
                if account.company_type != '':
                    #获得经营类目的名称
                    catalog_ids = json.loads(account.company_type)
                    for catalog_id in catalog_ids:
                        catalog_names.append(
                            catalog_id2name.get(catalog_id, ''))
                catalog_names = ','.join(catalog_names)

                #客户来源
                if company_name2info.has_key(account.company_name):
                    customerFrom = company_name2info[account.company_name]
                else:
                    customerFrom = '渠道' if account.customer_from == 1 else '--'  #如果从渠道没有找到匹配的,给默认值
            else:
                catalog_names = '--'
            if is_for_list:
                rows.append({
                    'id':
                    account.id,
                    'name':
                    account.name,
                    'companyName':
                    account.company_name,
                    'username':
                    user_id2username[account.user_id],
                    'companyType':
                    catalog_names,
                    'purchaseMethod':
                    METHOD2NAME[account.purchase_method]
                    if account.role == 1 else '--',
                    'createdAt':
                    account.created_at.strftime("%Y-%m-%d %H:%M:%S"),
                    'status':
                    account.status,
                    'maxProduct':
                    account.max_product if account.role == CUSTOMER else '--',
                    'customerFrom':
                    customerFrom
                })
            else:  #导出
                rows.append({
                    'id':
                    account.id,
                    'user_id':
                    account.user_id,
                    'phone':
                    account.phone,
                    'name':
                    account.name,
                    'contacter':
                    account.contacter,
                    'purchase_method':
                    METHOD2NAME[account.purchase_method]
                    if account.role == 1 else '--',
                    'username':
                    user_id2username[account.user_id],
                    'role':
                    ROLE2NAME[account.role],
                    'createdAt':
                    account.created_at.strftime("%Y-%m-%d %H:%M:%S"),
                    'note':
                    account.note,
                    'company_name':
                    account.company_name,
                    'companyType':
                    catalog_names
                })
        if is_for_list:
            data = {'rows': rows, 'pagination_info': pageinfo.to_dict()}
            #构造response
            response = create_response(200)
            response.data = data
            return response.get_response()
        else:
            return rows
예제 #8
0
def getProductRelationData(request, is_export):
	cur_page = request.GET.get('page', 1)
	first_catalog_id = request.GET.get('first_catalog_id', '')
	second_catalog_id = request.GET.get('second_catalog_id', '')
	user_info = UserProfile.objects.filter(user_id=request.user.id)
	if user_info:
		role = user_info[0].role
	else:
		role = 1
	user_profiles = UserProfile.objects.filter(role=1, is_active=True)#role{1:客户}
	if first_catalog_id != '':
		catalog_ids = [catalog.id for catalog in product_catalog_models.ProductCatalog.objects.filter(father_id=int(first_catalog_id))]
		products = models.Product.objects.filter(catalog_id__in=catalog_ids, is_deleted=False).order_by('-id')
	elif second_catalog_id != '':
		products = models.Product.objects.filter(catalog_id=int(second_catalog_id), is_deleted=False).order_by('-id')
	else:
		products = models.Product.objects.filter(is_deleted=False).order_by('-id')
	filter_dict = dict([(db_util.get_filter_key(key, filter2field), db_util.get_filter_value(key, request)) for key in request.GET if key.startswith('__f-')])
	product_name = filter_dict.get('product_name','')
	customer_name = filter_dict.get('customer_name','')
	product_status_value = filter_dict.get('product_status','0')
	catalog_name = filter_dict.get('catalog_name','')
	#查询
	if product_name:
		products = products.filter(product_name__icontains=product_name)
	if customer_name:
		user_profiles = user_profiles.filter(name__icontains=customer_name)
		user_ids = [user_profile.user_id for user_profile in user_profiles]
		products = products.filter(owner_id__in=user_ids)
	if catalog_name:
		product_catalogs = product_catalog_models.ProductCatalog.objects.filter(name__icontains=catalog_name)
		father_id2ids = {}
		for product_catalog in product_catalog_models.ProductCatalog.objects.all():
			if product_catalog.father_id not in father_id2ids:
				father_id2ids[product_catalog.father_id] = [product_catalog.id]
			else:
				father_id2ids[product_catalog.father_id].append(product_catalog.id)
		catalog_ids = []
		for product_catalog in product_catalogs:
			catalog_id = product_catalog.id
			# 查询的是二级分类
			catalog_ids.append(catalog_id)
			catalog_ids.append(product_catalog.father_id)
			# 查询的是一级分类
			if catalog_id in father_id2ids:
				catalog_ids.extend(father_id2ids[catalog_id])
		products = products.filter(catalog_id__in=catalog_ids)
	if int(product_status_value)!=0:
		sync_weapp_accounts = models.ProductSyncWeappAccount.objects.all()
		has_sync_p_ids = set([sync_weapp_account.product_id for sync_weapp_account in sync_weapp_accounts])

		has_relation_weapps = models.ProductHasRelationWeapp.objects.all()
		has_relation_p_ids = set([has_relation_weapp.product_id for has_relation_weapp in has_relation_weapps])
		if int(product_status_value)==1:#已入库,已同步
			products = products.filter(id__in=has_sync_p_ids)

		if int(product_status_value)==3:#已入库,已停售
			products = products.filter(id__in=has_relation_p_ids)
			products = products.exclude(id__in=has_sync_p_ids)
			
		if int(product_status_value)==2:#待入库
			products = products.exclude(id__in=has_relation_p_ids)
			products = products.exclude(id__in=has_sync_p_ids)
			products = products.exclude(is_refused=True)

		if int(product_status_value)==4:#入库驳回
			products = products.exclude(id__in=has_sync_p_ids)
			all_reject_p_ids = [product.id for product in products.filter(is_refused=True)] #所有驳回状态的id
			all_has_reject_p_ids = [reject_log.product_id for reject_log in models.ProductRejectLogs.objects.filter(product_id__in=all_reject_p_ids)] #是入库驳回的商品id
			products = products.filter(id__in=all_has_reject_p_ids)

		if int(product_status_value)==5:#修改驳回
			products = products.filter(id__in=has_sync_p_ids)
			sync_reject_p_ids = [product.id for product in products.filter(is_refused=True)] #所有驳回状态的id
			products = products.filter(id__in=sync_reject_p_ids)

	if not is_export:
		pageinfo, products = paginator.paginate(products, cur_page, 10, query_string=request.META['QUERY_STRING'])
	p_ids = [product.id for product in products]
	p_has_relations = models.ProductHasRelationWeapp.objects.filter(product_id__in=p_ids).exclude(weapp_product_id='')

	sync_weapp_accounts = models.ProductSyncWeappAccount.objects.filter(product_id__in=p_ids)
	weapp_relations = models.ProductHasRelationWeapp.objects.filter(product_id__in=p_ids)
	has_relation_p_ids = set([sync_weapp_account.product_id for sync_weapp_account in sync_weapp_accounts])
	weapp_relation_ids = [p.product_id for p in weapp_relations]
	has_reject_p_ids = [reject_log.product_id for reject_log in models.ProductRejectLogs.objects.filter(product_id__in=p_ids)]

	#从weapp获取销量sales_from_weapp
	id2sales = sales_from_weapp(p_has_relations)

	#获取标签
	property_ids = []
	catalog_ids = [product.catalog_id for product in products]
	product_catalog_has_labels = product_catalog_models.ProductCatalogHasLabel.objects.filter(catalog_id__in=catalog_ids)
	product_has_labels = models.ProductHasLabel.objects.filter(product_id__in=p_ids)
	
	catalog_property_ids = [product_catalog_has_label.property_id for product_catalog_has_label in product_catalog_has_labels]
	product_property_ids = [product_has_label.property_id for product_has_label in product_has_labels]
	property_ids.extend(catalog_property_ids)
	property_ids.extend(product_property_ids)
	label_group_values = label_models.LabelGroupValue.objects.filter(property_id__in=property_ids, is_deleted=False)
	value_id2name = {label_property_value.id:label_property_value.name for label_property_value in label_group_values}
		
	#分类配置的标签
	catalog_id2names = {}
	for product_catalog_has_label in product_catalog_has_labels:
		label_ids = product_catalog_has_label.label_ids.split(',')
		property_id = product_catalog_has_label.property_id
		catalog_id = product_catalog_has_label.catalog_id
		names = []
		for label_id in label_ids:
			if label_id and int(label_id) in value_id2name:
				names.append(value_id2name[int(label_id)])

		if catalog_id not in catalog_id2names:
			catalog_id2names[catalog_id] = names
		else:
			catalog_id2names[catalog_id].extend(names)

	#商品配置的标签 展示商品配置优先
	product_id2label_names = {}
	for product_has_label in product_has_labels:
		label_ids = product_has_label.label_ids.split(',')
		property_id = product_has_label.property_id
		label_product_id = product_has_label.product_id
		lanel_names = []
		for label_id in label_ids:
			if label_id and int(label_id) in value_id2name:
				lanel_names.append(value_id2name[int(label_id)])

		if label_product_id not in product_id2label_names:
			product_id2label_names[label_product_id] = lanel_names
		else:
			product_id2label_names[label_product_id].extend(lanel_names)

	#获取分类
	product_catalogs = product_catalog_models.ProductCatalog.objects.all()
	id2product_catalog = {product_catalog.id:product_catalog for product_catalog in product_catalogs}

	p_owner_ids = [product.owner_id for product in products]
	user_profiles = user_profiles.filter(user_id__in=p_owner_ids)
	user_id2name = {user_profile.user_id:user_profile.name for user_profile in user_profiles}
	# user_id2account_id = {user_profile.user_id:user_profile.id for user_profile in user_profiles}

	#获取下架商品的原因
	product_revoke_logs = models.ProductRevokeLogs.objects.filter(product_id__in=p_ids)
	#只取最后一次下架原因
	product_id2revoke_reasons = {revoke_log.product_id:revoke_log.revoke_reasons for revoke_log in product_revoke_logs}

	reject_logs = models.ProductRejectLogs.objects.filter(product_id__in=p_ids)
	product_id2reject_reasons = {}
	for reject_log in reject_logs:
		if product_id2reject_reasons.has_key(reject_log.product_id):
			product_id2reject_reasons[reject_log.product_id].append({
				'reject_reasons': reject_log.reject_reasons,
				'created_at': reject_log.created_at.strftime('%Y-%m-%d %H:%M:%S')
			})
		else:
			product_id2reject_reasons[reject_log.product_id] = [{
				'reject_reasons': reject_log.reject_reasons,
				'created_at': reject_log.created_at.strftime('%Y-%m-%d %H:%M:%S')
			}]

	#从渠道接口获得客户来源字段
	company_name2info = {}
	company_names = []
	for user_profile in user_profiles:
		if user_profile.company_name != '':
			company_names.append(user_profile.company_name)
	company_names = '_'.join(company_names)
	company_name2info = get_info_from_axe(company_names)

	#组装数据
	rows = []
	for product in products:
		owner_id = product.owner_id
		catalog_id = product.catalog_id
		if owner_id in user_id2name:
			sales = 0 if product.id not in id2sales else id2sales[product.id]
			product_status_text = u'待入库'
			product_status_value = 0
			if product.id in has_relation_p_ids:
				product_status_text = u'已入库,已同步'
				product_status_value = 1
				if product.is_refused:
					product_status_text = u'修改驳回'
					product_status_value = 4
			elif product.id not in has_relation_p_ids and product.id in weapp_relation_ids:
				product_status_text = u'已入库,已停售'
				product_status_value = 2
			elif product.id in has_reject_p_ids and product_status_value == 0 and product.is_refused:
				product_status_text = u'入库驳回'
				product_status_value = 3
			#商品分类
			first_level_name = ''
			second_level_name = ''
			if catalog_id in id2product_catalog:
				product_catalog = id2product_catalog[catalog_id]
				father_id = product_catalog.father_id
				second_level_name = product_catalog.name
				first_level_name = '' if father_id not in id2product_catalog else id2product_catalog[father_id].name

			#标签
			if product.id not in product_id2label_names:
				property_value_names = [] if catalog_id not in catalog_id2names else catalog_id2names[catalog_id]
			else:
				property_value_names = [] if product.id not in product_id2label_names else product_id2label_names[product.id]
			
			#组织成json格式
			label_names = []
			for property_value_name in property_value_names:
				label_names.append({
					'name': property_value_name
				})


			customer_from_text = '--' 
			#客户来源
			account = user_profiles.get(user_id=owner_id)
			if company_name2info.has_key(account.company_name):
				customer_from_text = company_name2info[account.company_name]
			else:
				customer_from_text = '渠道' if account.customer_from == 1 else '--' #如果从渠道没有找到匹配的,给默认值

			#驳回原因
			revoke_reasons = ''
			if product_status_value == 0: #待入库
				revoke_reasons = [{
					'reject_reasons': u'暂无记录',
					'created_at': ''
				}]
				revoke_reasons = json.dumps(revoke_reasons) if product.id not in product_id2reject_reasons else json.dumps(product_id2reject_reasons[product.id])
			elif product_status_value == 2: #已入库,已停售
				revoke_reasons = '' if product.id not in product_id2revoke_reasons else product_id2revoke_reasons[product.id]
			elif product_status_value == 3: #入库驳回
				revoke_reasons = json.dumps(product_id2reject_reasons[product.id])
			
			rows.append({
				'id': product.id,
				'role': role,
				'owner_id': owner_id,
				'catalogId': catalog_id,
				'product_name': product.product_name,
				'customer_name': '' if owner_id not in user_id2name else user_id2name[owner_id],
				'total_sales': '%s' %sales,
				'product_status': product_status_text,
				'product_status_value': product_status_value,
				'first_level_name': first_level_name,
				'second_level_name': second_level_name,
				'is_update': product.is_update,
				'customer_from_text': customer_from_text,
				'revoke_reasons': revoke_reasons,
				'labelNames': [] if not label_names else json.dumps(label_names)
			})
	if is_export:
		return rows
	else:
		return rows, pageinfo
	def api_get(request):
		is_for_list = True if request.GET.get('is_for_list') else False
		cur_page = request.GET.get('page', 1)
		accounts = UserProfile.objects.filter(is_active=True, role=1, product_count=0).order_by('created_at')
		catalogs = catalog_models.ProductCatalog.objects.filter(father_id=-1)
		catalog_id2name = dict((catalog.id,catalog.name) for catalog in catalogs)
		filters = dict([(db_util.get_filter_key(key, filter2field), db_util.get_filter_value(key, request)) for key in request.GET if key.startswith('__f-')])
		name = filters.get('name','')
		username = filters.get('username','')

		if name:
			accounts = accounts.filter(name__icontains=name)
		if username:
			user_ids = [user.id for user in User.objects.filter(username__icontains=username)]
			accounts = accounts.filter(user_id__in=user_ids)

		if is_for_list:
			pageinfo, accounts = paginator.paginate(accounts, cur_page, COUNT_PER_PAGE)

		user_ids = [account.user_id for account in accounts]
		user_id2username = {user.id: user.username for user in User.objects.filter(id__in=user_ids)}
		rows = []
		for account in accounts:
			catalog_names = []
			if account.company_type != '':
				#获得经营类目的名称
				catalog_ids = json.loads(account.company_type)
				for catalog_id in catalog_ids:
					catalog_names.append(catalog_id2name.get(catalog_id, ''))
			catalog_names = ','.join(catalog_names)
			if is_for_list:
				if account.role == 1 :
					catalog_names = []
					if account.company_type != '':
						#获得经营类目的名称
						catalog_ids = json.loads(account.company_type)
						for catalog_id in catalog_ids:
							catalog_names.append(catalog_id2name.get(catalog_id, ''))
					catalog_names = ','.join(catalog_names)
				else:
					catalog_names = '--'
				rows.append({
					'id' : account.id,
					'name' : account.name,
					'username' : user_id2username[account.user_id],
					'companyType' : catalog_names,
					'purchaseMethod' : METHOD2NAME[account.purchase_method] if account.role == 1 else '--',
					'accountType' : ROLE2NAME[account.role],
					'status' : account.status,
					'maxProduct': account.max_product if account.role == CUSTOMER else "--",
					'customerFrom': '渠道' if account.customer_from == 1 else '--',
					'productCount': account.product_count
				})
			else:
				rows.append({
					'id' : account.id,
					'user_id' : account.user_id,
					'phone' : account.phone,
					'name' : account.name,
					'contacter' : account.contacter,
					'purchase_method' : METHOD2NAME[account.purchase_method] if account.role == 1 else '--',
					'username' : user_id2username[account.user_id],
					'role' : ROLE2NAME[account.role],
					'note' : account.note,
					'company_name': account.company_name,
					'productCount': account.product_count
				})
			
		if is_for_list:
			data = {
				'rows': rows,
				'pagination_info': pageinfo.to_dict()
			}
			#构造response
			response = create_response(200)
			response.data = data
			return response.get_response()
		else:
			return rows
예제 #10
0
	def api_get(request):
		cur_page = request.GET.get('page', 1)
		filter_idct = dict([(db_util.get_filter_key(key, filter2field), db_util.get_filter_value(key, request)) for key in request.GET if key.startswith('__f-')])
		status = filter_idct.get('status',-1)
		# recommend_time = filter_idct.get('recommend_time__range','')
		user_has_fans = fans_models.UserHasFans.objects.filter(user_id=request.user.id)
		#查询
		if status != -1:
			user_has_fans = user_has_fans.filter(status=status)

		pageinfo, user_has_fans = paginator.paginate(user_has_fans, cur_page, 10, query_string=request.META['QUERY_STRING'])
		fans_id = [fans.fans_id for fans in user_has_fans]
		user_ids = [user.user_id for user in user_has_fans]
		fans = fans_models.Fans.objects.filter(id__in=fans_id)
		fans_id2fans = {fan.id:fan for fan in fans}

		products = product_models.Product.objects.filter(owner_id__in=user_ids)
		product_ids = [product.id for product in products]
		product_id2name = {product.id:product.product_name for product in products}

		product_has_relations = product_models.ProductHasRelationWeapp.objects.filter(product_id__in=product_ids).exclude(weapp_product_id='')
		product_weapp_id2product_id = {}
		for product_has_relation in product_has_relations:
			weapp_product_ids = product_has_relation.weapp_product_id.split(';')
			for weapp_product_id in weapp_product_ids:
				#获得所有绑定过云商通的云商通商品id
				product_weapp_id2product_id[weapp_product_id] = product_has_relation.product_id

		user_profiles = account_models.UserProfile.objects.filter(user_id__in=user_ids, is_active=True)
		account_ids = [user_profile.id for user_profile in user_profiles]
		account_has_suppliers = account_models.AccountHasSupplier.objects.filter(account_id__in=account_ids)
		supplier_ids = []
		for account_has_supplier in account_has_suppliers:
			if str(account_has_supplier.supplier_id) not in supplier_ids:
				supplier_ids.append(str(account_has_supplier.supplier_id))

		supplier_ids = '_'.join(supplier_ids)
		if supplier_ids != '':
			orders = []
			try:
				params = {
					'supplier_ids': supplier_ids
				}
				r = requests.post(ZEUS_HOST+'/panda/order_export_by_supplier/',data=params)
				res = json.loads(r.text)
				if res['code'] == 200:
					orders = res['data']['orders']
				else:
					print(res)
			except Exception,e:
				print(e)
			print('===orders===',orders)
			order_id2order = {}
			if orders:
				for order in orders:
					order_id = order['order_id']
					product_infos = order['products']
					total_count = 0
					total_order_money = 0
					product_name = ''
					purchase_price = 0
					for product in product_infos:
						total_count += product['count']
						weapp_product_id = str(product['id'])
						product_id = -1 if weapp_product_id not in product_weapp_id2product_id else product_weapp_id2product_id[weapp_product_id]
						product_name = product['name'] if product_id not in product_id2name else product_id2name[product_id]
						purchase_price = product['purchase_price']
						order_money = product['count'] * purchase_price
						total_order_money += order_money

					order_id2order[order_id] = {
						'order_id': order_id,
						'product_name': product_name,
						'purchase_price': '%.2f' %purchase_price,
						'total_count': total_count,
						'total_order_money': '%.2f' %total_order_money,
						'status': order_status2text[order['status']]
					}