o
    Q?h'                     @   s2  d dl Z d dlZd dlmZ d dlZd dlmZmZ d dlmZ d dl	m
Z
mZ d dlmZmZmZmZmZ d dlmZmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZmZ d ddZi fddZ dd Z!dd Z"dd Z#d dl Z d dlm$Z$ d dl%m&Z& de&de'de(e' fddZ)de$de'fddZ*dS )!    N)datetime)SERVER_TIMESTAMPdb)getItemCost)productsLastUpdatedsaveProductsLastUpdated)convertImageconvertProductconvertPropertyconvertVariantsaveProduct)	API_Error	saveError)
apiVersioncreateHeader)getShops)worker)SHOPIFY_API_VERSIONvalidate_shopify_idc                 C   sJ   ||pi d}t j| ||d}t|j |jdkr| S td|j )z$Execute a GraphQL query or mutation.)query	variables)jsonheaders   zGraphQL request failed: )requestspostprinttextstatus_coder   	Exception)urlr   r   r   payloadresponse r#   R/var/www/html/riverr-enterprise-integrations-main/V2/functions/Shopify/Products.pyexecute_graphql   s   

r%   c                 C   s(   dd t dddD }tt|}t|S )z-Update all products for active Shopify shops.c                 S   s   g | ]	}| d s|qS )disabled)get).0shopr#   r#   r$   
<listcomp>   s    z%updateAllProducts.<locals>.<listcomp>2T)
platformIdcredentials)r   r   updateShopProductsstr)paramsshopsresr#   r#   r$   updateAllProducts   s   
r3   c                 C   s  | rg }|  d}|  d}|  d}|  d dt d}t|}t|}t| d }| d}	d}
| d	r?|nd d
d}zt|||
|}|d d d }|D ]}|d }| dd}t|||  d|  d| d| d|t	| dt
| dg d dd | di  dg D d}| di  dg }g }|D ])}|d }dd | dg D }t|d |d |d ||d  d d!}|| q|t|| qVt|t||	d" d#t| W S  ty } zt|d$t|t||d%d& t|W  Y d }~S d }~ww d S )'NuididaccessTokenr    z/admin/api/z/graphql.json	timestampai  
        query($updatedAtMin: DateTime, $first: Int!) {
          products(first: $first, query: $updatedAtMin) {
            edges {
              node {
                id
                title
                descriptionHtml
                createdAt
                updatedAt
                tags
                images(first: 10) {
                  edges {
                    node {
                      id
                      originalSrc
                      position
                    }
                  }
                }
                variants(first: 10) {
                  edges {
                    node {
                      id
                      sku
                      inventoryItem {
                        id
                      }
                      price
                      selectedOptions {
                        name
                        value
                      }
                    }
                  }
                }
              }
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
        existed   )updatedAtMinfirstdataproductsedgesnodedescriptionHtml r,   enterpriseIdtitle	createdAttagsc                 S   s6   g | ]}t |d  d |d  d dk|d  d dqS )r?   originalSrcposition   r5   )r    primaryr5   )r   )r(   imager#   r#   r$   r*   w   s    

z&updateShopProducts.<locals>.<listcomp>images)r4   shopIdr,   rB   platformProductIdnamedescriptionrD   	updatedAtrE   pricerK   variantsc                 S   s    g | ]}t |d  |d dqS )rN   value)rN   rS   )r
   )r(   optr#   r#   r$   r*      s    selectedOptionsrQ   skuinventoryItem)r5   rQ   rV   
propertiesinventory_item_id)r7   zProducts Updated => z#Shopify/Products/updateShopProducts)rL   
lastUpdate)error)r'   r   r   r   r   fromtimestamp	isoformatr%   r	   fromisoformatr   r   appendr   r   lenr   r   r/   dict)r)   updatesr4   rL   r6   r    r   rZ   updated_at_minlastOrderTimestampr   r   r<   r=   product_edgeproductrO   convertedProductrR   convertedVariantsvariant_edgevariantrX   convertedVarianter#   r#   r$   r.   #   sx   



.


r.   c                 C   B   d}||d}t | |||}|d d d }|rtd| dS )z/Update SKU for a Shopify variant using GraphQL.a  
    mutation($variantId: ID!, $sku: String!) {
      productVariantUpdate(input: {id: $variantId, sku: $sku}) {
        productVariant {
          id
          sku
        }
        userErrors {
          field
          message
        }
      }
    }
    )	variantIdrV   r<   productVariantUpdate
userErrorszErrors updating variant SKU: Tr%   r   )r    r   
variant_idrV   mutationr   r"   errorsr#   r#   r$   updateVariantSku   s   
ru   c                 C   rm   )z0Update cost for an inventory item using GraphQL.aW  
    mutation($inventoryItemId: ID!, $cost: Float!) {
      inventoryItemUpdate(input: {id: $inventoryItemId, unitCost: {amount: $cost, currencyCode: "USD"}}) {
        inventoryItem {
          id
          unitCost {
            amount
          }
        }
        userErrors {
          field
          message
        }
      }
    }
    )inventoryItemIdcostr<   inventoryItemUpdaterp   z Errors updating inventory cost: Trq   )r    r   rY   rw   rs   r   r"   rt   r#   r#   r$   updateItemCostOnShopify   s   
ry   )ShopifyGraphQLClient)Shopr)   	productIdvariantsIdsc                 C   st   t | }d}||d}|||}|di di dg }|r,td| d|  ntd| d	 td
 dS )z
    Deletes all variants of a given Shopify product.
    
    :param shop: ShopifyGraphQLClient instance
    :param product_id: Shopify Product ID (e.g., "gid://shopify/Product/1234567890")
    aS  
    mutation bulkDeleteProductVariants($productId: ID!, $variantsIds: [ID!]!) {
        productVariantsBulkDelete(productId: $productId, variantsIds: $variantsIds) {
            product {
            id  
            title
            }
            userErrors {
            field
            message
            }
        }
        }
    )r}   r|   r<   productVariantDeleterp   zError deleting variant z: zDeleted variant z successfully.z"All variants deleted successfully.N)rz   executer'   r   )r)   r|   r}   graphql_clientrs   r   resultrt   r#   r#   r$   delete_all_variants   s   
r   clientc                 C   sT   d}dt |di}| ||}|di di di dg }dd	 |D }|S )
z
    Fetches all variants of a given Shopify product.

    :param shop: ShopifyGraphQLClient instance
    :param product_id: Shopify Product GID (e.g., "gid://shopify/Product/1234567890")
    :return: List of variants with their details
    a  
      query getProductVariants($productId: ID!) {
        product(id: $productId) {
          variants(first: 100) {
            edges {
              node {
                id
                title
                sku
                inventoryQuantity
                inventoryItem {
                  id
                }
              }
            }
          }
        }
      }
    r|   Productr<   rf   rR   r>   c                 S   s>   g | ]}|d  d |d  d |d  d |d  d d dqS )r?   r5   rC   rV   rW   )r5   rC   rV   rv   r#   )r(   vr#   r#   r$   r*     s    


z-getShopifyProductVariants.<locals>.<listcomp>)r   r   r'   )r   r|   r   r   r   rR   formatted_variantsr#   r#   r$   getShopifyProductVariants   s   	$
r   )N)+r   	tracebackr   r   configs.firebaser   r   functions.Enterprisesr   functions.LastUpdatedr   r   functions.Productsr   r	   r
   r   r   functions.Responser   r   functions.Shopify.Authr   r   functions.Shopsr   !functions.Suppliers.BlankProductsr   V2.functions.Shopify.mainr   r   r%   r3   r.   ru   ry   rz   V2.functions.Shops.mainr{   r/   listr   r   r#   r#   r#   r$   <module>   s.    

}"