o
    KOZh=                     @   s  d dl Z d dlZd dlZd dlmZ d dlZd dlmZ d dlmZm	Z	m
Z
 d dl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 d dl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l%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl%m&Z&m,Z, dZ-d dl.mZm/Z/m0Z0 d dl1m2Z2 d8de3de4fddZ5de4fddZ6de7fdd Z8d!d" Z9d dl Z d d#l:m,Z,m;Z;m<Z< i di i dfd$e+d%e=fd&d'Z>d(e,fd)d*Z?d(e,d+e3fd,d-Z@g i fd.d/ZAd9d0d1ZBg i fd2d3ZCd4d5 ZDg g g fd$e+fd6d7ZEdS ):    N)datetime)OAuth1Session)SERVER_TIMESTAMP
ArrayUniondb)getAppCredentials)getEnterpriseByIdgetItemCost)getProductRefsaveProduct	API_Error)getFulfillmentService)getShopById)wooAPI)createAttributescreateVariants)Application)submitToEtsy)ProductVariant)delete_all_variants)ENTERPRISESPLANS)Shop)r   ShopifyGraphQLClientz2023-07)r   updateFulfillmentLocationsgetShopLocations)submitToSquarespace
platformIdvariantsc                    s  ddddddddddddddd	d
 t | fddd}| dkr~g }d}d}i }|D ]@}|d}	|d}
|d}t|dt|dd|	gdt|dd|
gdgtt|d|dddddgd}|| q*tt|t||g| d| dS | dkrg }t }t }t }|D ]?}|dd	 }	|dd	 }
|d}t
|d}|
|	f|vr||
|	||d  ||
|	f ||
 ||	 qd!t|d"dt|d"g}||d#S | d$krPg }g }i }g }|D ]A}|d}
|d}	|d}|d%}||t
|< ||
 ||	 |tt
|d|tdd&|	d'td!d&|
d'gd( qtdd&d&tt|d)td!d&d&tt|d)g}|||fS d S )*Nr                           )XSSSMALLMEDIUMMLLARGEXLXXL2XLXXXL3XLr3   4XL5XLc                    s     t|  d dS )Nsize)getstrupper)variant
size_order U/var/www/html/riverr-enterprise-integrations-main/functions/products/SubmitProduct.py<lambda>#       z#generate_variants.<locals>.<lambda>key1i  i  r7   colorskuSize)property_idproperty_namedisplay_namevalueszPrimary Colorpricequantityd   )rM   rN   
is_enabled
is_deleted)rG   property_values	offerings,)
listing_idproductsprice_on_propertysku_on_property2 )option1option2rM   rG   ColornamerL   )r    options3mappingT)r_   	variationoption)regular_pricerG   
attributes)r_   rc   visibler`   )sortedr9   dictfloatappendintjsondumpssetstripr:   addlist)r   r    rU   kwargsformatted_variantssize_property_idcolor_property_idmappingsr<   r7   rF   rG   unique_variantscolorssizesrM   r`   rb   rf   r?   r=   r@   generate_variants!   s   $


"&



%









r{   imagesc           	   	   C   s   t  }g }| D ]<}|d}|d}t|j}| d| }t|d}|| |t||d W d    n1 s?w   Y  q||fS )Nurlr_   /wb)r_   image)	tempfilemkdtempr9   requestscontentopenwriterk   ri   )	r|   pathimage_pathsr   srcr_   r   
image_name
image_filer?   r?   r@   
tempImages   s   


r   paramsc           -      C   sN  |  d}| d| d}}|  dg }|stdd|  d}t |}|j}t|}| d}	t ||	tv s>|tv r@d	n| }
|sOtd
dt|di }|D ]}| d}d }d }|dkrjt	| dnd }|dkrwt	| dnd }zVt
d|  }|jstddt|d| }dd |jd  D }dd |jd  D }dd |jd  D }| d d}i }|D ]	}|t| qi }| D ]"\}}| d}| d}|r|r| | }||v r|| ||< q| dg r| dg n	| d i  d!g }| d"} d#d |jd$  D }!|dkrtd]i d|d%|
d&|d'| d(d)| d i  d)d*d"| d"d+d,|  d,d-d.|d/| d/d0d1d2|d3|d|d4d5d6d7d8d9d:d;d<d=d>d?d$|!}"|"\}}n|d@krt| d(| d i  d)d*||| d/||!| |||dA}"|"\}}nn|dBkrt| d(| d)d*| |!| d/g |dC}"|"\}}nM|dDkrt| d(| d)d*||!| d/g |dC}"|"\}}n.|dEkrt| d(| d)d*||| d/g dFd |jd2  D dG}"|"\}}ntdH|r|r| d}#|d = |d= |dI= | dJr7|dJ= | dKr@|dK= t|||}$|$|d< ||dL< ||dM< ||d< t|dN< t|dO< ||dP< |$|#d< g }%dQd |jd2  D }&g }'| D ]&}(t| |(})| |(}*|& |(}+|)|+d< |)|*d< |%|+ |'|* q{t||%}$t|#|'||!dR |jtt|gt|$gdS tdTdU|j  dVdW||$dX||< W qS ty }, zt!|,j" t||,j"|,j#|,j$dYd dZ||< W Y d },~,qSd },~,w t%y! }, zt!|, t!t&'  t|t|,i d[dYd dZ||< W Y d },~,qSd },~,ww t|d\S )^NcurrentUseruidenterpriseIdmanualProductszNo Products Selected.  shopIdplanIdzNAlxdaZG6hKf6vexv6ljqHyP8i1zShop not found.i  )r   idrE   
taxanomyIdshippingTemplateIdzSelected product not found.r   c                 S   s   g | ]}|  qS r?   )to_dict).0pr?   r?   r@   
<listcomp>      z!submitProduct.<locals>.<listcomp>
placementsc                 S   s   g | ]}d |j i| qS )rG   r   r   r   vr?   r?   r@   r         
variationsc                 S      i | ]}|j | qS r?   r   r   r?   r?   r@   
<dictcomp>      z!submitProduct.<locals>.<dictcomp>variantsMappingproductMappingblankProductIdsblankProductIdblankVariantIdr|   productDetailsavatarsrM   c                 S   s    i | ]}|j | d g qS r|   )r   r   r9   )r   docr?   r?   r@   r          colorImagesappshoptitler_   descriptionrZ   
   rN   rO   taxonomy_idtagsstateactiver    shipping_template_iditem_weightr%   item_weight_unitozitem_length   
item_width   item_heightr"   item_dimensions_unitinrY   )r_   r   r|   r   r   r    r   rM   r   weightsr   ra   )r_   r   r   r   r   r    1013c                 S   s   g | ]	}t | qS r?   )r   	from_dictr   r   r?   r?   r@   r   h  rB   )r_   r   r   r|   r   r    zUnsupported platform.selectedBlankNicknamesactiveShopsactiveProductsplatformProductIdr   	createdAt	updatedAtparentProductIdc                 S   r   r?   r   r   r?   r?   r@   r     r   )r   )r   r      zListing added to .T)status_codemessagesuccessr   	productIdF)r   r   metar   r   r   i  )	responsesr?   )(r9   r   r   r   r   r   r   r   ri   rl   r   
collectiondocumentexistsr   	referenceupdategetBlankVariantWeightsitemsr   submitToShopifysubmitToWoocommercer   addToPopupStorer
   r   keysr:   rk   r   saveProductMappingr   r_   printr   r   r   	Exception	traceback
format_exc)-r   r   r   r   r   r   r   r   
enterpriser   r   r   manualProductmanualProductIdr   platformVariants
taxonomyIdr   manualProductRefr   r   r   r   r   r   variant_weights
variant_idvariant_datablank_product_idblank_variant_idrD   r|   rM   r   responser   r   convertedVariantsr    mappedVariantsrG   	variantIdvariantMappingr<   er?   r?   r@   submitProduct   s  



"



.



	























r   c                    s(   t d  d } fdd|D S )NzblankProducts/z/blankVariantsc                    s&   i | ]}t  |j | d qS )weight)r:   r   r   r9   )r   blankVariantr   r?   r@   r     s    z*getBlankVariantWeights.<locals>.<dictcomp>)r   r   r9   )r   blankVariantsr?   r   r@   r     s   
r   )r   
shopifyGidshopifyNumIdr   returnc           &      C   s  ddl m} ddlm} t| }td|}d}d|||ddd	 |d
d dD dddd	 |d
d dD dgddi}|||}|di di dg }|r`|t|d|d d d d }||
d| j	d| j	id}t
|}dd	 |D }dd | D }d}g }|dD ]P}d d	 |D }|||d!r||d!g d ng |d" d|d#d$d|d!d$gd%|d |d" |d& d'd(t|	|d& dd)d*id+d, q|d-d	 t| g D |d.}|||}|di d/i dg }|r|t|dd0}td1| |di }|s+|d2t| d|d/i d3g } | D ]}!|!d4d}"|D ]}#|||"|#d5}$td6|$ qCq7d7d |d d/ d3 D }%t|| t||%fS )8Nr   )Paramsr   rY   aF  
        mutation productCreate($input: ProductInput!) {
            productCreate(input: $input) {
                product {
                    id
                    title
                    variants(first: 10) {
                        edges {
                            node {
                                id
                                title
                            }
                        }
                    }
                }
                userErrors {
                    field
                    message
                }
            }
        }
    inputrH   c                 S      g | ]}d |iqS r_   r?   r   valuer?   r?   r@   r     r   z#submitToShopify.<locals>.<listcomp>r`   r!   rL   r^   r]   c                 S   r  r  r?   r  r?   r?   r@   r     r   ACTIVE)r   descriptionHtmlr   productOptionsstatusdataproductCreate
userErrorsr   productr   shopifyr   )r   hostnamer   argsc                 S   s.   g | ]}| d r| dsd|d  qS )r   legacyzgid://shopify/Location/r   r9   )r   locr?   r?   r@   r     s   . c                 S   s    i | ]\}}|d d |D qS )c                 S   s   g | ]}| d qS )r}   r  r   ir?   r?   r@   r         z.submitToShopify.<locals>.<dictcomp>.<listcomp>r?   )r   rF   r|   r?   r?   r@   r     r   z#submitToShopify.<locals>.<dictcomp>a  
       mutation ProductVariantsCreate($media:[CreateMediaInput!], $productId:ID!, $variants: [ProductVariantsBulkInput!]!) {
        productVariantsBulkCreate(media:$media, productId: $productId, variants: $variants, strategy: REMOVE_STANDALONE_VARIANT) {
            productVariants {
                id
                title
                sku
                selectedOptions {
                    name
                    value
                }
                inventoryItem {
                    id
                }
            }
            userErrors {
                field
                message
            }
        }
    }
    r    c                 S   s   g | ]}d |dqS )2   )availableQuantity
locationIdr?   )r   loc_idr?   r?   r@   r     s    r[   rM   r\   )
optionNamer_   CONTINUErG   Tr   OUNCES)r  unit)costrG   trackedmeasurement)mediaSrcrM   optionValuesinventoryPolicyinventoryQuantitiesinventoryItemc                 S   s   g | ]}|d dqS )IMAGE)originalSourcemediaContentTyper?   )r   imgr?   r?   r@   r     r  )r   mediar    productVariantsBulkCreatea$  
    mutation inventoryActivate($inventoryItemId: ID!, $locationId: ID!) {
      inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId) {
        inventoryLevel {
          id
        }
        userErrors {
          field
          message
        }
      }
    }
    variant_resultzShopify returned no data: productVariantsr)  )inventoryItemIdr  z
Activated:c                 S   s   i | ]}|d  t |d qS )rG   r   )r  r   r?   r?   r@   r   6  r   )	V2.Paramsr  functions.Responser   r   r{   r9   executer:   r   r   r   rk   rj   sumrL   r   publishProductToOnlineStorer  )&r   r_   r   r   r    r|   r   rM   r   r   r   r  r   graphql_clientgenerated_variantsproduct_create_mutationproduct_variablesresulterrors
product_idr   	locationslocation_idsvariantImagesvariants_create_mutationvariant_inputsr   inventory_quantitiesvariant_variablesr0  activate_mutationr  variants_datar<   inventory_item_idr  activation_resultvariants_mapr?   r?   r@   r     s   

(


r   clientc                 C   sT   d}|  |}|di di dg D ]}|ddkr%|d  S qtd)	Nzu
    query {
      publications(first: 10) {
        nodes {
          id
          name
        }
      }
    }
    r  publicationsnodesr_   zOnline Storer   z&Online Store publication ID not found.)r5  r9   r   )rK  queryr<  pubr?   r?   r@   getOnlineStorePublicationId;  s   

 rP  
productGidc              
   C   s   t | }d}d|t|dgdi}z.| ||}|di di dg }|r5td| d	|  W d S td
| d W d S  ty^ } ztd| d	t|  W Y d }~d S d }~ww )Na  
    mutation productPublish($input: ProductPublishInput!) {
        productPublish(input: $input) {
            product {
                id
            }
            productPublications {
                channel {
                    name
                }
                isPublished
            }
            userErrors {
                    field
                    message
                }
            }
        }
    r  )publicationId)r   productPublicationsr  publishablePublishr  u   ❌ Failed to publish product z: u   ✅ Product z published to Online Store.u!   ❌ Exception publishing product )rP  ri   r5  r9   r   r   r:   )rK  rQ  onlineStorePublicationIdmutation	variablesr<  r=  r   r?   r?   r@   r7  L  s(   &r7  c                    s  |  d}td|\}}}	g }
dd |D  | D ]\}|
fdd|D  qt|||
d|dd	 |D ttd
d |D d}|  d|  d|  d}}t||}i }|D ]
}|t	|| q_|
d|}i }|jdv r| }| d}
| d}d| d}|	D ]"dd	  dD d<  fdd	|
D }|r|d nd d< qt|||	}|	D ]|  d| d< qt||fS t|j|j)Nr}   ra   c                 S   s   i | ]}| d | dqS )rG   rF   r  r   r<   r?   r?   r@   r     r   z'submitToWoocommerce.<locals>.<dictcomp>c                 3   s"    | ]}t  |d dV  qdS )r}   )r_   r   Nri   r9   r  rC   r?   r@   	<genexpr>  s    
z&submitToWoocommerce.<locals>.<genexpr>variablec                 S   s   g | ]}t |d qS )r  )ri   )r   tagr?   r?   r@   r   #  r  z'submitToWoocommerce.<locals>.<listcomp>c                 s   s    | ]}| d V  qdS )rM   Nr  r   r?   r?   r@   rZ  $  s    )r_   r   r|   typerf   r   re   consumerKeyconsumerSecretrV   )r      r|   r   z	products/z/variationsc                 S   s$   g | ]}t |d |ddqS )r_   rd   )r_   rd   rY  )r   	attributer?   r?   r@   r   3  s    rf   c                    s6   g | ]}   d | dkrt| ddqS )rG   r_   r   r   )r9   ri   )r   r   )	colorSkusr<   r?   r@   r   :  s   6 r   r   rG   )r9   r{   r   extendri   r:   minr   r   r   postr   rm   r   r   text)r   r_   r   r    r   r   r}   rf   _rt   r|   imgespayloadsecretwcapiattsra  r  r   variant_imagescreatedVariantsr?   )rb  rD   r<   r@   r     sP   

"	



r   c           	      C   sb   |  dt  d| d} t|d}|r||d< |r||d< t|d}tj| t||d}t|jS )	N/admin/api/
/products//images.json)variant_idsr   
attachment)r   r  headers)
apiVersionri   r   re  rm   rn   r   rf  )	r}   ru  r   
variantIdsr   rs  r   r  resr?   r?   r@   connectionVariantImageB  s   


ry  c           
      C   s   |  d}td|}||  |D ]}|d| d| q|D ]}|d| d| q'| D ]\}}	|d|t|	d q<|S )Nr   productsMappingr   r   r   r   )r9   r   r   r   ro   r   ri   )
r   r   r   r   r   refr   	placementrF   r|   r?   r?   r@   r   K  s   

&&r   c                 C   sz   |  dt  d| d}dd|dii}tj|t||d}|jdkr+| dS | }tt|d	i 	 |j)
Nro  rp  rq  r   rs  r}   rt  r`  r=  )
rv  r9   r   re  rm   rn   r   r   r:   rL   )r}   headerr   r   	image_url
image_datarequestr  r?   r?   r@   addNewProductImageU  s   

r  c           	      C   s   t tt  }|j|j | }t||jd|j|j	|| |t t t
dd |D ||d}|dd |D  |dd |D fS )Nr   c                 S   s   g | ]}|j qS r?   )rM   rX  r?   r?   r@   r   x  s    z#addToPopupStore.<locals>.<listcomp>)r   r   r   r   r   r   r_   r   r   r   rM   r|   r   c                 S   s   g | ]}t |qS r?   )r   r   rX  r?   r?   r@   r   |  r  c                 S   s   i | ]}|j |j qS r?   r   rX  r?   r?   r@   r   }  r  z#addToPopupStore.<locals>.<dictcomp>)r:   rl   r   now	timestampr   r   r   r   r   rd  save)	r_   r   r   r|   r   r    r   r   r  r?   r?   r@   r   c  s&   r   )N)NN)Frm   r   r   r   r    requests_oauthlib.oauth1_sessionr   configs.firebaser   r   r   functions.Applicationsr   functions.Enterprisesr   r	   functions.Productsr
   r   r4  r   functions.Shopify.Fulfillmentr   functions.Shopsr   functions.WooCommerce.Authr   functions.WooCommerce.Productsr   r   V2.functions.Applications.mainr   V2.functions.Etsy.Productsr   V2.functions.Products.mainr   r   V2.functions.Shopify.Productsr   V2.functions.Shops.Authr   r   V2.functions.Shops.mainr   r   rv  V2.functions.Shopify.Locationsr   r   !V2.functions.Squarespace.Productsr   r:   rr   r{   r   ri   r   r   V2.functions.Shopify.mainr   r  tupler   rP  r7  r   ry  r   r  r   r?   r?   r?   r@   <module>   st     = D Q
 = I
.	
