Exemplo n.º 1
0
 def try_connect(self, logger: AirbyteLogger, config: dict):
     session = shopify.Session(f"{config['shop']}.myshopify.com", "2021-01",
                               config["api_key"])
     shopify.ShopifyResource.activate_session(session)
     # try to read the name of the shop, which should be available with any level of permissions
     shopify.GraphQL().execute("{ shop { name id } }")
     shopify.ShopifyResource.clear_session()
def delete_products(gid):
    product = '''
                    input: {
                        id: "''' + gid + '''"
                    }
                '''

    del_prod_mutation = '''
                            mutation {
                                productDelete(''' + product + '''){
                                    deletedProductId
                                    shop {
                                      id
                                    }
                                    userErrors {
                                      field
                                      message
                                    }
                                }
                            }
                        '''
    db.session.delete(Product.query.filter_by(gid=gid).first())
    db.session.commit()
    client = sfy.GraphQL()
    result = client.execute(del_prod_mutation)
    print('deletd product: ', gid)
Exemplo n.º 3
0
    def products_update(self, data):
        product_id = data.get('id')
        title = data.get('title')
        vendor = data.get('vendor')
        p_type = data.get('product_type')
        try:
            product = Product.objects.get(store=self._user,
                                          product_id=product_id)
            product.title = title
            product.vendor = vendor
            product.type = p_type

            if product.image is None:
                client = shopify.GraphQL()
                query = '''
                    query {
                        product(id: "gid://shopify/Product/%s") {
                            id
                            featuredImage {
                                transformedSrc(maxWidth: 50)
                            }
                        }
                    }
                ''' % product_id

                result = json.loads(client.execute(query))['data']['product']
                image = result['featuredImage']

                product.image = image

            product.save()
            print("Product updated: %s" % product.id)
        except Exception as e:
            print(e)
Exemplo n.º 4
0
 def get(self, request, *args, **kwargs):
     client = shopify.GraphQL()
     query = '''
         {
             products(first: 10)  {
                 edges   {
                     node    {
                         id
                         handle
                         title
                     }
                 }
             }
             productVariants(first:10){
                 edges{
                 node{
                     title
                 }
                 }
             }
         }
     '''
     test = ['test', 'test']
     result = client.execute(query)
     result = ast.literal_eval(result)
     result['data']['products']['edges'][0]['node']['test'] = test
     return Response(result['data'])
Exemplo n.º 5
0
def get_collections_by_product_id(product_id):
    query = '''{
        product(id: "%s") {
            collections(first: 50) {
                edges { 
                    node { 
                        id 
                        title 
                    }
                }
            }
        }
    }
    '''

    result = shopify.GraphQL().execute(query % product_id)
    data = json.loads(result)

    collections = []
    if 'data' in data and 'product' in data['data'] and data['data']['product'] is not None and 'collections' in \
            data['data']['product'] \
            and 'edges' in data['data']['product']['collections'] and len(
        data['data']['product']['collections']['edges']):
        for item in data['data']['product']['collections']['edges']:
            if 'node' in item:
                collections.append({
                    "id": item['node']['id'],
                    "title": item['node']['title'],
                })

    return collections
def delete_customer(gid):
    customer = '''
                    input: {
                        id: "''' + gid + '''"
                    }
                '''

    del_cust_mutation = '''
                            mutation {
                                customerDelete(''' + customer + '''){
                                    deletedCustomerId
                                    shop {
                                      id
                                    }
                                    userErrors {
                                      field
                                      message
                                    }
                                }
                            }
                        '''
    db.session.delete(Customer.query.filter_by(gid=gid).first())
    db.session.commit()
    client = sfy.GraphQL()
    result = client.execute(del_cust_mutation)
    print(result)
Exemplo n.º 7
0
def get_collections_by_id_list(set_collection_ids):
    set_collection_ids = set(set_collection_ids)

    query = '{'
    for idx, collection_id in enumerate(set_collection_ids):
        query += '''
        collection%s: collection(id: "%s") {
            id
            title
        }
        ''' % (idx, collection_id)
    query += '}'

    result = shopify.GraphQL().execute(query)
    data = json.loads(result)
    collections = {}

    if 'data' in data:
        for i in range(0, len(set_collection_ids)):
            if 'collection' + str(i) in data['data'] and data['data'][
                    'collection' + str(i)] is not None:
                item = data['data']['collection' + str(i)]

                if item:
                    collections[item['id']] = {
                        "id": item['id'],
                        "title": item['title'],
                    }

    return collections
Exemplo n.º 8
0
def complete_draft_order(order_gid):
    """
        Take any draft order id and complete it using a GQL request
    """
    print('draft order gid: ', order_gid)
    draft_order = '''
                    id: "''' + order_gid + '''"
                '''

    order_mutation = '''mutation {
                                    draftOrderComplete(''' + draft_order + ''')
                                        {
                                            draftOrder {
                                                        id
                                                    }
                                            userErrors {
                                                        field
                                                        message
                                                    }
                                        }
                                    }
                            '''
    pprint(order_mutation)
    client = sfy.GraphQL()
    result = json.loads(client.execute(order_mutation))

    pprint(result)
def get_orders():
    orders = '''
                    {
                      draftOrders(first: 10, reverse: true) {
                        edges {
                          node {
                            id
                            createdAt
                            metafields(first:10, namespace:"testing date") {
                              edges {
                                node {
                                    key
                                    value
                                }
                              }
                            }
                          }
                        }
                      }
                    }
            '''
    # pprint(order_mutation)
    # shop_session = sfy.Session(shop_url, '2019-04', shop_token)
    # activate the shopify session to use resources.
    # sfy.ShopifyResource.activate_session(shop_session)
    client = sfy.GraphQL()
    return json.loads(client.execute(orders))
Exemplo n.º 10
0
def get_products_by_id_list(product_id_list):
    product_id_set = set(product_id_list)

    query = '{'
    for idx, product_id in enumerate(product_id_set):
        query += '''
        product%s: product(id: "%s") {
            id
            title
            status
        }
        ''' % (idx, product_id)
    query += '}'

    result = shopify.GraphQL().execute(query)
    data = json.loads(result)
    products = []

    if 'data' in data:
        for i in range(0, len(product_id_set)):
            if 'product' + str(i) in data['data'] and data['data'][
                    'product' + str(i)] is not None:
                item = data['data']['product' + str(i)]

                if item:
                    products.append({
                        "id": item['id'],
                        "title": item['title'],
                    })

    return products
Exemplo n.º 11
0
 def setUp(self):
     super(GraphQLTest, self).setUp()
     shopify.ApiVersion.define_known_versions()
     shopify_session = shopify.Session("this-is-my-test-show.myshopify.com",
                                       "unstable", "token")
     shopify.ShopifyResource.activate_session(shopify_session)
     client = shopify.GraphQL()
     self.fake(
         "graphql",
         method="POST",
         code=201,
         headers={
             "X-Shopify-Access-Token": "token",
             "Accept": "application/json",
             "Content-Type": "application/json",
         },
     )
     query = """
         {
             shop {
                 name
                 id
             }
         }
     """
     self.result = client.execute(query)
Exemplo n.º 12
0
def get_product_by_id(product_id):
    query = '''{
        product(id: "%s") {
            id
            title
            status
            featuredImage {
                originalSrc
                transformedSrc(maxWidth:160, crop: CENTER)
            }
        }
    }
    '''

    result = shopify.GraphQL().execute(query % product_id)
    data = json.loads(result)

    product = None
    if 'data' in data and 'product' in data['data'] and data['data'][
            'product'] is not None:
        product = {
            "id": data['data']['product']['id'],
            "title": data['data']['product']['title'],
            "featured_image": data['data']['product']['featuredImage']['originalSrc'] \
                if data['data']['product']['featuredImage'] is not None and 'originalSrc' in data['data']['product'][
                'featuredImage'] else None,
            "thumbnail": data['data']['product']['featuredImage']['transformedSrc'] \
                if data['data']['product']['featuredImage'] is not None and 'transformedSrc' in data['data']['product'][
                'featuredImage'] else None,
        }

    return product
Exemplo n.º 13
0
def get_products_by_type(type, first, after='', search=''):
    query = """{
        products(%s) {
            pageInfo {
                hasNextPage
                hasPreviousPage
            }
            edges {
                cursor
                node {
                    id
                    title
                    featuredImage {
                        originalSrc
                        transformedSrc(maxWidth:160, crop: CENTER)
                    }
                }
            }
        }
    }
    """

    pagination = f'first: {first}' if after == '' else f'first: {first}, after: "{after}"'
    query_params = f'query: "product_type:{type}"' if search == '' else f'query: "product_type:{type}, title:{search}*"'

    result = shopify.GraphQL().execute(query % f'{pagination}, {query_params}')
    data = json.loads(result)
    pagination = None
    products = []

    if 'data' in data and 'products' in data['data']:
        if 'pageInfo' in data['data']['products']:
            pagination = data['data']['products']['pageInfo']

        if 'edges' in data['data']['products'] and len(
                data['data']['products']['edges']):
            for item in data['data']['products']['edges']:
                if 'node' in item:
                    products.append({
                        "cursor":
                        item['cursor'],
                        "id":
                        item['node']['id'],
                        "title":
                        item['node']['title'],
                        "featured_image":
                        item['node']['featuredImage']['originalSrc']
                        if item['node']['featuredImage'] is not None
                        and 'originalSrc' in item['node']['featuredImage'] else
                        None,
                        "thumbnail":
                        item['node']['featuredImage']['transformedSrc']
                        if item['node']['featuredImage'] is not None
                        and 'transformedSrc' in item['node']['featuredImage']
                        else None,
                    })

    return {'pagination': pagination, 'products': products}
Exemplo n.º 14
0
def get_orders(limit, after=None, status=''):
    if after:
        query = '{ orders(first:%LIMIT%, after: %AFTER%, query:"financial_status:AUTHORIZED") { edges { node { id displayFinancialStatus } } }}'
    else:
        query = '{ orders(first: %LIMIT%) {    edges { cursor node { id   }    }  }}'
    query = query.replace('%LIMIT%', str(limit))

    if after:
        query = query.replace('%AFTER%', after)

    result = shopify.GraphQL().execute(query)
    print(result)
    return json.loads(result)
Exemplo n.º 15
0
 def check_config(self, logger: AirbyteLogger, config_path: str, config: json) -> AirbyteConnectionStatus:
     try:
         session = shopify.Session(f"{config['shop']}.myshopify.com", "2020-10", config["api_key"])
         shopify.ShopifyResource.activate_session(session)
         # try to read the name of the shop, which should be available with any level of permissions
         shopify.GraphQL().execute("{ shop { name id } }")
         shopify.ShopifyResource.clear_session()
         return AirbyteConnectionStatus(status=Status.SUCCEEDED)
     except Exception as e:
         logger.error(f"Exception connecting to Shopify: ${e}")
         return AirbyteConnectionStatus(
             status=Status.FAILED, message="Unable to connect to the Shopify API with the provided credentials."
         )
Exemplo n.º 16
0
def gen_order(customer_gid, variant_list, completed_date, shop_url,
              shop_token):
    """
        Creates a single order
    """
    line_items_string = ''
    for item in variant_list:
        line_item = gen_order_line_item(item[0].gid, item[1])
        line_items_string += '{variantId:  "%s",  quantity: %i }' %\
                            (line_item['variantId'], line_item['quantity'])
    # print(line_items_string)

    draft_order = '''
                input: {
                    customerId: "''' + customer_gid + '''",
                    metafields: {
                        description: "date",
                        key: "date",
                        namespace: "testing date"
                        value: "''' + completed_date + '''",
                        valueType: STRING
                    },
                    lineItems:[''' + line_items_string + ''']
                }
                '''
    # pprint(draft_order)
    order_mutation = '''mutation {
                                    draftOrderCreate(''' + draft_order + ''')
                                        {
                                            draftOrder {
                                                        id
                                                    }
                                            userErrors {
                                                        field
                                                        message
                                                    }
                                        }
                                    }
                            '''
    # pprint(order_mutation)
    shop_session = sfy.Session(shop_url, '2019-04', shop_token)
    # activate the shopify session to use resources.
    sfy.ShopifyResource.activate_session(shop_session)
    client = sfy.GraphQL()
    result = json.loads(client.execute(order_mutation))

    pprint(result)
    order_id = result['data']['draftOrderCreate']['draftOrder']['id']
    db.session.add(Order(gid=order_id))
    db.session.commit()
    complete_draft_order(order_id)
Exemplo n.º 17
0
    def get(self, request, *args, **kwargs):
        client = shopify.GraphQL()
        query = '''
            {
		        shop	{
				    id
				    name
				    email
		        }
            }
        '''
        result = client.execute(query)
        result = ast.literal_eval(result)
        return Response(result['data'])
Exemplo n.º 18
0
def get_products_by_collection(collection):
    query = """{
        collection(id: "%s") {
            handle
            products(first: 100) {
                edges { 
                    node { 
                        id
                        title
                        status
                        featuredImage {
                            originalSrc
                            transformedSrc(maxWidth:160, crop: CENTER)
                        }
                    } 
                }
            }
        }
    }
    """

    result = shopify.GraphQL().execute(query % collection)
    data = json.loads(result)

    products = []

    if 'data' in data and 'collection' in data['data'] and data['data']['collection'] is not None and 'products' in \
            data['data']['collection'] \
            and 'edges' in data['data']['collection']['products'] \
            and len(data['data']['collection']['products']['edges']):
        for item in data['data']['collection']['products']['edges']:
            if 'node' in item and item['node']['status'] == 'ACTIVE':
                products.append({
                    "id":
                    item['node']['id'],
                    "title":
                    item['node']['title'],
                    "featured_image":
                    item['node']['featuredImage']['originalSrc']
                    if item['node']['featuredImage'] is not None and
                    'originalSrc' in item['node']['featuredImage'] else None,
                    "thumbnail":
                    item['node']['featuredImage']['transformedSrc']
                    if item['node']['featuredImage'] is not None
                    and 'transformedSrc' in item['node']['featuredImage'] else
                    None,
                })

    return products
Exemplo n.º 19
0
 def get(self, request, *args, **kwargs):
     client = shopify.GraphQL()
     query = '''
         {
             customers(first:1){
                 edges{
                 node{
                     email
                     displayName
                 }
                 }
             }
         }
     '''
     result = client.execute(query)
     result = ast.literal_eval(result)
     return Response(result['data'])
Exemplo n.º 20
0
def upload_product_data(prod_name, max_variants=10):
    """
        Upload a single product to the shop
        input:
         - prod_name: name for the fake name creation
         - max_variants: maximum number of variants to allow this product to have
        returns:
         - graphQL post result containint the product id, shop id, and any errors
    """

    product_mutation = '''mutation {
                                    productCreate(input: {
                                        descriptionHtml: "test product generated via GraphQL",
                                        title: "''' + prod_name + '''"
                                        }
                                    )
                                    {
                                        product{
                                            id
                                        }
                                        shop {
                                            id
                                        }
                                        userErrors{
                                            field
                                            message
                                        }
                                    }
                            }

                        '''
    # print(sfy.ShopifyResource.get_site())
    client = sfy.GraphQL()
    product_results = json.loads(client.execute(product_mutation))
    # print(product_results)
    pid = product_results['data']['productCreate']['product']['id']
    #add this product to the database
    prod = Product(gid=pid, name=prod_name)
    db.session.add(prod)
    db.session.commit()
    #determine number of variants
    for v in range(random.randint(0, max_variants)):
        generate_fake_variant(pid,"Variant Test generate with GraphQL {}".format(v),\
                                    "variant: {}".format(v), "6.69", "2.38")

    return product_results
Exemplo n.º 21
0
def generate_fake_variant(productId, option, variant_sku, variant_price,
                          variant_cost):
    """
        Upload a single product to the shop
    """
    variant_mutation = '''mutation {
                                productVariantCreate(input: {
                                        productId: "''' + productId + '''",
                                        options: "''' + option + '''",
                                        price:"''' + variant_price + '''",
                                        sku: "''' + variant_sku + '''",
                                        inventoryItem: {
                                            cost: "''' + variant_cost + '''"
                                        }

                                    })
                                    {
                                        product{
                                            id
                                        }
                                        productVariant{
                                            id
                                        }
                                        userErrors{
                                            field
                                            message
                                        }
                                    }
                            }

                        '''

    client = sfy.GraphQL()
    # result = client.execute(variant_mutation)
    var_results = json.loads(client.execute(variant_mutation))
    # print(product_results)
    # print(var_results)
    vid = var_results['data']['productVariantCreate']['productVariant']['id']
    #upload this product's variants to the DATABASE
    var = Variant(gid=vid, name=variant_sku)
    prod = Product.query.filter_by(gid=productId).first()
    db.session.add(var)
    prod.variants.append(var)
    db.session.commit()
    return var_results
Exemplo n.º 22
0
    def excute_graph_ql(self, query: str) -> dict:
        try:
            # the execute function sometimes prints and this causes errors for the target, so I block printing for it
            with HiddenPrints():
                response = json.loads(shopify.GraphQL().execute(query))
        except Exception:
            raise GraphQLGeneralError("Execution failed", code=500)

        if 'data' in response and response['data'] is not None:
            return response['data']

        if "errors" in response:
            errors = response["errors"]
            singer.log_info(errors)
            if errors[0]["extensions"]["code"] == "THROTTLED":
                raise GraphQLThrottledError("THROTTLED", code=429)

        raise GraphQLGeneralError("Failed", code=500)
Exemplo n.º 23
0
def get_products_by_tag(tag):
    query = """{
        products(first: 100, query: "tag:%s") {
            edges {
                node {
                    id
                    title
                    featuredImage {
                        originalSrc
                        transformedSrc(maxWidth:160, crop: CENTER)
                    }
                }
            }
        }
    }
    """
    if not isinstance(tag, list):
        tag = [tag]

    result = shopify.GraphQL().execute(query % tag)
    data = json.loads(result)
    products = []

    if 'data' in data and 'products' in data['data'] and 'edges' in data[
            'data']['products'] and len(data['data']['products']['edges']):
        for item in data['data']['products']['edges']:
            if 'node' in item:
                products.append({
                    "id":
                    item['node']['id'],
                    "title":
                    item['node']['title'],
                    "featured_image":
                    item['node']['featuredImage']['originalSrc']
                    if item['node']['featuredImage'] is not None and
                    'originalSrc' in item['node']['featuredImage'] else None,
                    "thumbnail":
                    item['node']['featuredImage']['transformedSrc']
                    if item['node']['featuredImage'] is not None
                    and 'transformedSrc' in item['node']['featuredImage'] else
                    None,
                })

    return products
Exemplo n.º 24
0
    def cron_fetch_abandoned_cart(self):
        todayStr = datetime.today().strftime('%Y-%m-%d')
        checkout = self.env['whatsapp.shopify.checkout'].sudo().search(
            [('id', '>', 0)], order="checkout_iden desc", limit=1)

        shops = self.env['shopify_app.shop'].sudo().search([('id', '>', 0)])
        for shop in shops:
            # get the offline access code
            token = shop['code']
            domain = shop['url']

            session = shopify.Session(domain, '2019-04', token)
            shopify.ShopifyResource.activate_session(session)

            checkouts = shopify.Checkout.find(updated_at_min=todayStr)

            updatedCheckouts = shopify.Checkout.find(since_id=12950897623172)
            checkoutCount = shopify.Checkout.get('count')

            client = shopify.GraphQL()
            query = '''
               {
                  products(first:10, query:"tag:rental") {
                    edges {
                      node {
                        id
                        title
                      }
                    }
                  }
                }
              '''
            result = client.execute(query)
            d = json.loads(result)
            if checkouts:
                for checkout in checkouts:
                    #update or create
                    cart_token = checkout.attributes['cart_token']
                    exist_checkout = self.sudo().search([('cart_token', 'like',
                                                          cart_token)])
                    if not exist_checkout:
                        #todo:
                        vals = {}
Exemplo n.º 25
0
def get_all_tags(limit, after=None):
    if after:
        query = '''
        {
            shop{
                productTags(first: %LIMIT%, after: %AFTER%){
                    edges{
                        node
                    }
                }
            }
        }
        '''
    else:
        query = '''
        {
            shop{
                productTags(first: %LIMIT%){
                    edges{
                        node
                    }
                }
            }
        }
        '''

    query = query.replace('%LIMIT%', str(limit))

    if after:
        query = query.replace('%AFTER%', after)

    result = shopify.GraphQL().execute(query)
    data = json.loads(result)

    tags = []
    if 'data' in data and 'shop' in data['data'] and 'productTags' in data['data']['shop'] and 'edges' in \
            data['data']['shop']['productTags'] \
            and len(data['data']['shop']['productTags']['edges']):
        for item in data['data']['shop']['productTags']['edges']:
            if 'node' in item:
                tags.append(item['node'])

    return tags
Exemplo n.º 26
0
def get_products():
    query = '''{
        products(first: 10) {
            edges {
                node {
                    createdAt
                    collections(first: 5) {
                        edges {
                            node {
                                id
                                handle
                                title 
                            }
                        }
                    }
                    description
                    featuredImage {
                        id
                        originalSrc
                        transformedSrc
                    }
                    id
                    isGiftCard
                    onlineStorePreviewUrl
                    onlineStoreUrl
                    productType
                    publishedAt
                    tags
                    title
                    totalInventory
                    updatedAt
                    vendor
                }
            }
        }
    }'''

    result = shopify.GraphQL().execute(query)
    data = json.loads(result)

    return data
Exemplo n.º 27
0
def get_collection_info_by_id(collection_id):
    query = '''{
        collection(id: "%s") {
            id 
            title 
        }        
    }
    '''

    result = shopify.GraphQL().execute(query % collection_id)
    data = json.loads(result)

    collection = None
    if 'data' in data and 'collection' in data['data'] and data['data'][
            'collection'] is not None:
        collection = {
            "id": data['data']['collection']['id'],
            "title": data['data']['collection']['title'],
        }

    return collection
Exemplo n.º 28
0
def orders_api_call_1():
    results = shopify.GraphQL().execute('''query {
        orders(first:20, reverse:true, query:"fulfillment_status:unshipped,fulfillment_status:Pending") {
            edges {
                node {
                    name
                    displayFulfillmentStatus

                    createdAt
                    displayAddress {
                        name
                    }
                }
            }
        }
    }    

    ''')
    payload = json.loads(results)
    order_ids = [i["node"]["name"] for i in payload['data']['orders']['edges']]
    fulfillment_status = [
        i["node"]["displayFulfillmentStatus"]
        for i in payload['data']['orders']['edges']
    ]
    order_created_time = [
        i["node"]["createdAt"] for i in payload["data"]["orders"]["edges"]
    ]
    order_create_date = [i.split("T")[0] for i in order_created_time]
    names = [
        i["node"]["displayAddress"]["name"]
        for i in payload["data"]["orders"]["edges"]
    ]
    df = pandas.DataFrame(list(
        zip(order_ids, fulfillment_status, order_create_date,
            order_created_time, names)),
                          columns=[
                              "order_ids", "fulfillment_status", "order_date",
                              "order_time_raw", "name"
                          ])
    return df
 def inventory_items_update(self, data):
     inventory_item_id = data.get('id')
     sku = data.get('sku').strip()
     tracked = data.get('tracked')
     try:
         if self._preferences.activate:
             variant = Variant.objects.get(store=self._user, inventory_item_id=inventory_item_id)
             variant.sku = sku
             variant.inventory_management = tracked
             if tracked:
                 variants = Variant.objects.filter(store=self._user, sku=sku, inventory_management=tracked)
                 for _ in variants:
                     if _.id != variant.id:
                         variant.qty = _.qty
                         break
                 if variants:
                     inv_item = shopify.InventoryLevel.find_first(inventory_item_ids=inventory_item_id)
                     shopify.InventoryLevel.set(
                         inventory_item_id=inventory_item_id,
                         location_id=inv_item.location_id,
                         available=variant.qty)
                 else:
                     client = shopify.GraphQL()
                     query = '''
                         query {
                             inventoryItem(id: "gid://shopify/InventoryItem/%s") {
                                 variant {
                                     inventoryQuantity
                                 }
                             }
                         }
                     ''' % inventory_item_id
                     result = json.loads(client.execute(query))['data']['inventoryItem']
                     variant.qty = result['variant']['inventoryQuantity']
                 variant.save()
             else:
                 variant.save()
             print('Inventory and sku synced for variant %s' % variant.id)
     except Exception as e:
         print(e)
Exemplo n.º 30
0
 def get(self, request, *args, **kwargs):
     client = shopify.GraphQL()
     query = '''
         {
             collections(first: 5){
                 edges{
                 node{
                     products (first: 5){
                     edges {
                         node {
                         id
                         }
                     }
                     }
                     title
                 }
                 }
             }
         }
     '''
     result = client.execute(query)
     result = ast.literal_eval(result)
     return Response(result['data'])