示例#1
0
def get_or_create_buyer(buyer_id: int, buyer_draw=dict()):
    store = Store()
    buyer = Buyer.objects.filter(id=buyer_id).first()
    if buyer and ((not buyer_draw) or (buyer.first_name)):
        return buyer

    if not buyer_draw:
        path = '/sites/MLV/search'
        params = {'seller_id': buyer_id}
        buyer_api = store.get(path, params)
        nickname = buyer_api['seller']['nickname']
        buyer = Buyer.objects.create(id=buyer_id, nickname=nickname)
    else:
        phone_draw = buyer_draw.get('phone')
        phone = ''
        if phone_draw.get('area_code'):
            phone += phone_draw.get('area_code').replace(' ', '')
        if phone_draw.get('number'):
            phone += phone_draw.get('number').replace('-', '').replace(' ', '')
        if len(phone) > 5:
            phone = int(phone)
        else:
            phone = 0

        if not buyer:
            buyer = Buyer.objects.create(
                id=buyer_id,
                nickname=buyer_draw.get('nickname'),
                phone=phone,
                first_name=buyer_draw.get('first_name'),
                last_name=buyer_draw.get('last_name'),
            )
        else:
            buyer.phone = phone
            buyer.nickname = buyer_draw.get('nickname')
            buyer.first_name = buyer_draw.get('first_name')
            buyer.last_name = buyer_draw.get('last_name')
            buyer.save()

    logging.getLogger('log_three').info(
        f'Comprador Actualizado/Registrado: {buyer}')

    return buyer
示例#2
0
    def handle(self, *args, **options):
        seller_id=config('MELI_ME_ID')
        store = Store(seller_id=seller_id)

        path = '/questions/search'
        params = {
            'seller_id':seller_id,
            'status':'UNANSWERED',
            'offset':0,
        }
        questions_api = store.get(path, params)

        total = questions_api['total']
        limit = questions_api['limit']

        questions_draw = questions_api['questions']

        params = [{
            'seller_id':seller_id,
            'status':'UNANSWERED',
            'offset':offset,
            'attributes':'questions'
        }for offset in range(limit,total,limit)]

        for questions_api in store.map_pool_get([path]*len(params), params):
            questions_draw += questions_api['questions']

        questions_draw = questions_draw[::-1]

        count=0
        for question_draw in questions_draw:
            question,exist =  new_question(question_draw)
            if exist:
                break
            else:
                logging.getLogger('log_three').info(f'Nueva Pregunta de {question.buyer} en \
{question.product.title} a las {question.date_created.strftime("%H:%M:%S")}')        
                count +=1

        logging.getLogger('log_three').info(f'Nuevas Preguntas: {count}. Sin responder: {total}')
示例#3
0
    def handle(self, *args, **options):
        seller_id = options['seller_id']
        store = Store(seller_id=seller_id)
        now = timezone.now()
        last_hour = now - timedelta(hours=1)
        params = {
            'seller': store.SELLER_ID,
            'order.date_created.from':
            f'{last_hour.strftime("%Y-%m-%d")}T{last_hour.strftime("%H")}:00:00.000-00:00',
            'order.date_created.to':
            f'{now.strftime("%Y-%m-%d")}T{now.strftime("%H")}:00:00.000-00:00',
            'sort': 'date_desc'
        }

        path = '/orders/search'
        orders_api_draw = store.get(path, params, auth=True)
        orders_api = orders_api_draw.get('results')
        for order_draw in orders_api:
            news_draw = list()
            offer_id = order_draw.get('id')
            buyer_api = order_draw.get('buyer')

            # REGISTRAR COMPRADOR
            buyer = get_or_create_buyer(int(buyer_api.get('id')), buyer_api)

            # VERIFICAR EXISTENCIA DEL PRODUCTO
            product_api = order_draw.get('order_items')[0]
            quantity = product_api['quantity']
            sku = product_api.get('item').get('id')
            product = ProductForStore.objects.filter(sku=sku).first()
            if not product:
                msg = f'El producto con sku={sku} no se encuentra en nuestra \
base de datos y fue orfertado bajo el pedido {offer_id} del comprador {buyer_api}'

                # LEVANTAR NOVEDAD
                logging.getLogger('log_three').warning(msg)
                continue

            USD = History.objects.order_by('-datetime').first()
            if product.sale_price * USD.country(
                    store.country) > product_api.get('unit_price'):
                # LEVANTAR NOVEDAD
                msg = f'El precio acortado por el producto con sku={sku} no es rentable.'
                news_draw.append(msg)
                logging.getLogger('log_three').warning(msg)

            res = store.verify_existence(product)
            if not res.get('ok'):
                # LEVANTAR NOVEDAD
                msg = f'El producto con sku={sku} esta agotado'
                news_draw.append(msg)
                logging.getLogger('log_three').warning(msg)

            order = Order.objects.filter(store_order_id=offer_id)
            if order:
                break

            pay = Pay.objects.create(amount=float(product_api['unit_price']))
            invoice = Invoice.objects.create(pay=pay)
            order = Order.objects.create(store_order_id=offer_id,
                                         product=product,
                                         quantity=quantity,
                                         buyer=buyer,
                                         invoice=invoice)
            for msg in news_draw:
                New.objects.create(user=store.attentive_user,
                                   message=msg,
                                   order=order)
示例#4
0
def new_pay( request, order_id):
    if request.method != 'POST':
        raise Http404
    json_data=json.loads(request.body)
    pay_reference = int(json_data.get('pay_reference'))
    quantity = int(json_data.get('quantity'))

    user_name = request.user.first_name
    if not (pay_reference and quantity):
        return JsonResponse({
            'ok': False,
            'msg': f'{user_name} Haz ingresado un dato incorrecto, verifica e intenta de nuevo'
        })
    
    order = Order.objects.filter(store_order_id=order_id).select_related('product').select_related('product__store').select_related('buyer').select_related('invoice').select_related('invoice__pay').first()
    if order.state >= Order.PROCESSING:
        return JsonResponse({
            'ok': False,
            'msg': f'{user_name} ya esta orden fue procesada. Contacta con un supervisor si deseas hacer cambios en ella.'
        })

    if order.state == Order.CANCELLED:
        return JsonResponse({
            'ok': False,
            'msg': f'Esta orden ya fue concelada. No se puede modificar su estado.'
        })

    if order.invoice.user:
        return JsonResponse({
            'ok': False,
            'msg': f'{user_name} ya esta orden contine un pago relacionado'
        })

    store = Store(seller_id=order.product.store.seller_id)
    params = {
        'attributes': 'date_created,buyer,order_items'
    }
    path = f'/orders/{order_id}'
    result = store.get(path,params, auth=True)
    buyer = order.buyer
    product_api = result.get('order_items')[0]
    product = order.product

    USD = History.objects.order_by('-datetime').first()
    if product.sale_price*USD.country(store.country) > product_api.get('unit_price'):
        msg = f'El producto ha subido de precio.'
        New.objects.create(
            user=request.user,
            message=msg,
            order=order
        )
        return JsonResponse({
            'ok': False,
            'msg': f'{user_name}. {msg}, Contacta con tu supervisor.',
        })

    # res = store.verify_existence(product)
    # if not res.get('ok'):
    #     New.objects.create(
    #         user=request.user,
    #         message=res.get("msg"),
    #         order=order
    #     )
    #     return JsonResponse({
    #         'ok': False,
    #         'msg': f'{user_name}, {res.get("msg")}',
    #     })

    pay = Pay.objects.filter(reference=pay_reference).first()
    if pay:
        msg = f'{user_name}. El numero de referencia de ese pago ya fue registrado anteriormente.'
        New.objects.create(
            user=store.attentive_user,
            message=msg,
            order=order
        )
        return JsonResponse({
            'ok': False,
            'msg': msg
    })

    order.invoice.pay.reference = pay_reference
    order.invoice.pay.save()

    order.quantity = quantity
    order.state = Order.PAID_OUT
    order.save()
    msg = f'Referencia de pago agregada correctamente.'
    New.objects.create(
        user=request.user,
        message=msg,
        order=order
    )

    return JsonResponse({
        'ok': True,
        'msg': f'{user_name}. {msg}'
    })