예제 #1
0
def new_answer(text, question, user):
    store = Store()
    path = '/answers'

    body = {
        'question_id': question.id,
        'text': text,
    }

    res = store.post(path, body, auth=True)

    if res.get('error'):
        return JsonResponse({
            'ok': False,
            'msg': f'{res.get("error")}:{res.get("message")}'
        })

    Answer.objects.create(user=user,
                          text=text,
                          question=question,
                          created_date=timezone.localtime())

    return JsonResponse({
        'ok': True,
        'msg': 'Respuesta Creada correctamente',
    })
예제 #2
0
 def __init__(self, scan_dir, work_dir):
     self.recog = Recog.recog16()
     self.store = Store()
     self.plot = Plot()
     self.work_dir = work_dir
     self.scanner = Scanner(scan_dir, work_dir)
     self.main_process()
예제 #3
0
def get_token(request):
    query = request.GET
    code = query.get('code')
    jwt_split = code.split('-')
    seller_id = jwt_split[2]
    store = Store(seller_id)
    store.authorize(code, Store.URI_CALLBACK)
    return HttpResponse('Autenticacion Exitosa!')
예제 #4
0
 def handle(self, *args, **options):
     seller_id = options['seller_id']
     store = Store(seller_id=seller_id)
     products = ProductForStore.objects.filter(
         status__in=(ProductForStore.ACTIVE, ProductForStore.UNDER_REVIEW))
     ids = products.values_list('sku', flat=True)
     total = len(ids)
     store.update_items(ids, [{'status': 'paused'}] * total)
     products.update(status=ProductForStore.PAUSED)
     logging.getLogger('log_three').info(f'{total} Productos Pausados')
예제 #5
0
    def handle(self, *args, **options):
        seller_id = options['seller_id']
        store = Store(seller_id=seller_id)
        products = ProductForStore.objects.filter(store_id=seller_id).exclude(
            sku=None)
        ids = products.values_list('sku', flat=True)
        params = [{
            'ids': _ids,
            'attributes': 'status,id'
        } for _ids in store.split_ids(ids)]
        path = 'items'

        results = store.map_pool_get([path] * len(params), params)
        posts = defaultdict(list)
        for product in [_ for _ in results if _]:
            if product['code'] == 200:
                if product['body']['status'] == 'closed':
                    posts['deleted'].append(product['body']['id'])
                elif product['body']['status'] == 'active':
                    posts['active'].append(product['body']['id'])
                elif product['body']['status'] == 'paused':
                    posts['paused'].append(product['body']['id'])
                elif product['body']['status'] == 'under_review':
                    posts['under_review'].append(product['body']['id'])
                elif product['body']['status'] == 'inactive':
                    posts['inactive'].append(product['body']['id'])
            else:
                logging.getLogger('log_three').info(product)

        logging.getLogger('log_three').info(
            f"{len(posts['deleted'])} Productos eliminados recientemente.")
        ProductForStore.objects.filter(sku__in=posts['deleted']).update(
            status=ProductForStore.CLOSED)

        logging.getLogger('log_three').info(
            f"{len(posts['active'])} Productos activos.")
        ProductForStore.objects.filter(sku__in=posts['active']).update(
            status=ProductForStore.ACTIVE)

        logging.getLogger('log_three').info(
            f"{len(posts['paused'])} Productos pausados.")
        ProductForStore.objects.filter(sku__in=posts['paused']).update(
            status=ProductForStore.PAUSED)

        logging.getLogger('log_three').info(
            f"{len(posts['under_review'])} Productos bajo revision de ML.")
        ProductForStore.objects.filter(sku__in=posts['under_review']).update(
            status=ProductForStore.UNDER_REVIEW)

        logging.getLogger('log_three').info(
            f"{len(posts['inactive'])} Productos inactivos por revision de ML."
        )
        ProductForStore.objects.filter(sku__in=posts['inactive']).update(
            status=ProductForStore.UNDER_REVIEW)
예제 #6
0
 def tests_store(self):
     parts = np.array(
         pd.read_csv("datasets/parts.csv", header=None, sep=","))
     samples = parts[np.random.randint(0, parts.shape[0], 20)]
     # print(samples)
     store = Store()
     for sample in samples:
         place_id = store.store(sample[0], np.random.rand(1, 10))
         part_id, count = store.lookup(place_id)
         # if count > 0:
         #     print("Test case part {}: Success!", sample)
         # else:
         #     print("Test case part {}: Failure!", sample)
         # self.assertTrue(count > 0)
     self.assertTrue(False)
예제 #7
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
예제 #8
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}')
    def handle(self, *args, **options):
        limit = options['limit']
        seller_id = options['seller_id']
        start = datetime.now()
        logging.getLogger('log_three').info(
            'Aplicando filtro de malas palabras a productos')
        filter_bad_products(seller_id)
        logging.getLogger('log_three').info(
            'Filtrado completado, tiempo de ejecucion {:.2f} seg'.format(
                (datetime.now() - start).total_seconds()))

        store = Store(seller_id=seller_id)
        start = datetime.now()
        logging.getLogger('log_three').info('Consultando la base de datos')
        products = ProductForStore.objects.exclude(sku=None).filter(
            product__quantity__gt=0,
            product__available=True,
            status=ProductForStore.PAUSED,
            sale_price__gt=0,
            store_id=seller_id)[:limit]
        logging.getLogger('log_three').info(
            'Fin de la consulta, tiempo de ejecucion {:.2f} seg'.format(
                (datetime.now() - start).total_seconds()))
        ids = products.values_list('sku', flat=True)
        total = products.count()
        results = store.update_items(ids, [{'status': 'active'}] * total)

        posts_active = list()
        for product in results:
            if product.get('status') == 'active':
                posts_active.append(product['id'])
            else:
                logging.getLogger('log_three').warning(
                    f'Producto no actualizado: {product}')

        ProductForStore.objects.filter(sku__in=posts_active).update(
            status=ProductForStore.ACTIVE)
        logging.getLogger('log_three').info(
            f"{len(posts_active)} Productos activados.")
예제 #10
0
    def handle(self, *args, **options):
        seller_id = options['seller_id']
        fields = options['fields']
        only_actives = options['only_actives']

        store = Store(seller_id=seller_id)
        products = ProductForStore.objects.filter(
            store=store.business_model).exclude(
                sku=None).select_related('product')
        if only_actives:
            products.filter(status=ProductForStore.ACTIVE)
        else:
            products.filter(
                status_in=[ProductForStore.ACTIVE, ProductForStore.PAUSED])

        bodys = dict()

        if 'price' in fields:
            update_stock(products, bodys, store)
            return store.update_items(list(bodys.keys()), list(bodys.values()))

        if 'description' in fields:
            update_descriptions(products, bodys, store)
            return store.update_items(list(bodys.keys()), list(bodys.values()))
예제 #11
0
    def handle(self, *args, **options):
        seller_id = options['seller_id']
        logging.getLogger('log_three').info('Aplicando filtro de malas palabras a productos')
        filter_bad_products(seller_id=seller_id)

        start = datetime.now()
        logging.getLogger('log_three').info('Consultando la base de datos')
        store = Store(seller_id=seller_id)
        business = BusinessModel.objects.get(pk=store.SELLER_ID)

        products = ProductForStore.objects.filter(
            store=business,
            sku=None,
            product__available=True,
            product__quantity__gt=2).select_related('product')
        logging.getLogger('log_three').info(f'Fin de la consulta, tiempo de ejecucion {datetime.now()-start}')

        slices = 100
        USD = History.objects.order_by('-datetime').first()
        price_usd = USD.country(business.country) + business.usd_variation

        limit_per_day = False
        with ThreadPoolExecutor(max_workers=3) as executor:
            for lap, _products in enumerate(chunks(products, slices)):
                logging.getLogger('log_three').info(f'PUBLICANDO {(lap)*slices}-{(lap+1)*slices}')
                response = executor.map(
                    store.publish,
                    _products,
                    [price_usd]*len(_products))
                for product in response:
                    if not product['ok'] and product.get('data'):
                        limit_per_day = (product['data'].get('message') ==  'daily_quota.reached')
                    if limit_per_day:
                        break
                if limit_per_day:
                        break
예제 #12
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)
예제 #13
0
def cancel_order(request):
    json_data=json.loads(request.body)
    message = json_data['message']
    order_id = int(json_data['orderId'])
    reason = int(json_data['reason'])
    rating = int(json_data['rating'])
    order = Order.objects.filter(store_order_id=order_id).select_related('product').select_related('product__store').first()
    if not order:
        return JsonResponse({
            'ok': False,
            'msg': 'El numero de pedido no existen. Esto debe ser un error, consulte al desarrollador.'
        })
    if order.state == order.CANCELLED:
        return JsonResponse({
            'ok': False,
            'msg': f'Esta orden ya fue cancelada anteriormente.'
        })

    if order.state > Order.OFFERED:
        return JsonResponse({
            'ok': False,
            'msg': f'Esta orden ya tiene un pago registrado, no es posible cancelar la misma.'
        })

    body = {
        'fulfilled':False,
        'message':'No se pudo concretar la venta',
        'reason':FeedBack.REASON_MELI[reason],
        'rating':'neutral',
    }

    store = Store(seller_id=order.product.store.seller_id)
    res = store.post(
        path=f'/orders/{order_id}/feedback',
        body=body,
        auth=True,
    )

    if res[0] == 'Feedback already exists':
        FeedBack.objects.create(
            raiting=rating,
            reason=reason,
            fulfilled=False,
            user=request.user,
            message=message,
            order=order
        )

        order.state = Order.CANCELLED
        order.save()
        return JsonResponse({
            'ok': True,
            'msg': 'Orden cancelada correctamente.',
            'data': []
        })
    else:
        return JsonResponse({
            'ok': False,
            'msg': res,
            'data': []
        })
예제 #14
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}'
    })
예제 #15
0
def login(request):
    store = Store()
    url = store.auth_url()
    return redirect(url)
예제 #16
0
import random
import json
from store.store import Store

store = Store()


class Actor:
    """
    male or female actor

    """
    def __init__(self, gender='male', name='', node_id=0):
        self.gender = gender
        self.name = name
        self.node_id = node_id
        ## irrelevant attributes
        ## also make the irrelevant attributes random. Not every entity will have them all
        self.attributes = {
            'work': '',
            'school': '',
            'location_born': '',
            'social_media_active': False,
            'social_media_preferred': '',
            'political_views': '',
            'hobby': '',
            'sport': '',
        }
        self.attribute_store = store.attribute_store
        self.fill_attributes()
예제 #17
0
 def __init__(self):
     self.store = Store()