o
    Q?h5                     @   s   d dl Z d dlmZ d dl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mZ d d	lmZ d d
lmZ d dlmZ dd Zdd Zdd Zdd Zdd ZdefddZdd Zdd Zdd Zdd  Z d!d" Z!dS )#    N)datetime)
PROJECT_ID)db)getAppCredentials)getEnterpriseById)	API_ErrorpriorityLogger)
apiVersioncreateHeader)getShopById)PLANS)Shopc                 C   s  |  d}|  d}|  d}| d| d}}t|}| dd}| d}t|tvr2d	| nd
}	t|}
|
r=|
S |sDt|d}tt| dtt	
   dddt dddd|	rxt|	 d|	 d|	 d|	 d|	 d|dnd d}t| d}d|d< | d dt d}tj|tt|dtt|d|d}|jd kr|  d!}
td"||
 |
S t|j|j| )#NshopIdcurrentUsershopuidenterpriseIdnamePODplanId22zNAlxdaZG6hKf6vexv6ljqHyP8i1Tz - Fulfillment Service Fz+https://riverr-enterprise-integrations-dot-z%.uc.r.appspot.com/shopify/fulfillmentjsonaddress1address2cityzipcountry_code)r   r   r   r   r   r   )r   inventory_managementtracking_supportcallback_urlrequires_shipping_methodformatfulfillment_orders_opt_inlocationaccessTokenzapplication/jsonzContent-Typeurl/admin/api/z/fulfillment_services.json)fulfillment_service)datar   headers   r(   fulfillmentServices)getr   r   r   getFulfillmentServicer   dictstrintr   now	timestampr   r
   r	   requestspostr   dumpsstatus_coder   
collectiondocumentsetr   text)r)   r   r   r   r   r   
enterpriser   r   appfulfillmentServiceservicer*   r&   res rA   R/var/www/html/riverr-enterprise-integrations-main/functions/Shopify/Fulfillment.pycreateFulfillmentService   sN   




*
rC   c                 C   s&   t d|  }|jr| S d S Nr,   )r   r8   r9   r-   existsto_dictr   refrA   rA   rB   r.   9   s   r.   c                 C   s6   |  dt  d} tj| |d}|jr| dS g S )Nr'   z//fulfillment_services.json?scope=current_clientr*   fulfillment_services)r	   r4   r-   okr   )r&   r*   r@   rA   rA   rB   getFulfillmentServices>   s   rL   c                 C   sR   |  dt  d} t||dd}tj| t||d}|jdkr!dS t|j| dS )Nr'   z/inventory_levels/connect.jsonT)location_idinventory_item_idrelocate_if_necessary)r)   r*   r+   F)	r	   r/   r4   r5   r   r6   r7   printr;   )r&   r*   itemId
locationIdr)   r@   rA   rA   rB   connectionInventoryLocationD   s   rS   c                 C   sX   t | d}| d dt d}t|||d}tj|||d}|jdkr*| S d S )Nr%   r&   r'   z/inventory_levels.json)rN   rM   	available)r   r*   r+   )r
   r-   r	   r/   r4   r5   r7   r   )r   rM   rQ   quantityr*   r&   r)   r@   rA   rA   rB   addInventoryL   s   
rV   r   c              	   C   s   t | j}t| j||}d }t|dkr|d d}nt| jdd|  td| t	j
| j dt d|ttt||dd	d
|igddd}|jdkrWtd| | S tdd|j||jjd t|j d S )Nr   idsubmitShopifyShipmentzNo fulfillment order found zNo fulfillment order foundr'   z/fulfillments.json)numbercompanyTfulfillment_order_id)tracking_infonotify_customerline_items_by_fulfillment_order)fulfillmentr*   r   r+   zShipment submitted to ShopifyNone)platformOrderIdr)   )r
   r%   getFulfillmentOrdersr&   lenr-   r   r   rP   r4   r5   r	   r/   r7   r   r;   requestbody)r   rb   carrierNametrackingNumberr*   fulfillmentOrdersfulfillmentOrderIdr@   rA   rA   rB   rX   U   s4   





rX   c                 C   sR   t j|  dt d| d|d}|jdkr| dS tdd|j| ||d	 d S )
Nr'   z/orders/z/fulfillment_orders.jsonrI      fulfillment_ordersra   rc   )r&   r*   rb   )r4   r-   r	   r7   r   r   r;   )r&   r*   rb   r@   rA   rA   rB   rc      s   
rc   c                 C   s.   t d|  }|jr|j  |jS d S rD   )r   r8   r9   r-   rE   	referencedeleterW   )shoIdrH   rA   rA   rB   deleteFulfillmentService   s
   
rp   c                 C   s&   t d|   }|jr| S d S )NzfulfillmentServices/)r   r9   r-   rE   rF   rG   rA   rA   rB   getFulfillmentLocation   s   rq   c           
         s   t | }t| }|sd S |d t|j}t|j|d} fdd|D }g }|D ]}|j d|d d}tj||d}	|	|	j
 q+|S )NrW   rI   c                    s   g | ]}| d  kr|qS )rW   )r-   ).0lcurrentLocationIdrA   rB   
<listcomp>   s    z3removeWrongFulfillmentLocations.<locals>.<listcomp>z(/admin/api/2024-04/fulfillment_services/z.json)r   r-   rq   r
   r%   rL   r&   r4   rn   appendr;   )
r   r   currentLocationr*   	locationslocationsToRemove	responseslocationToRemover&   r@   rA   rt   rB   removeWrongFulfillmentLocations   s   


r}   c                 C   s  zt ddd|  }t| }td| |s!td|  d tdt| |s5td|  d W d	S t| d
}|d}|d}t|}|D ]p}|	 }|d}	| dt
 d}
t|
 d|	 d}tj|
|d|id}|jdkrtd|	 d|j  qJ| di di d}|dkrtd|	 d qJd|	 d}tj|
|d|id}|jdkrtd|	 d|j  qJ| di di dg }|std |	 d qJ|d! d" }d#| d$|d" d%}tj|
|d|id}|jdkr	td&| d|j  qJtd'|d"| | di d(i d)g }|r0td*| d+|  qJtd,| d-|d" d t d.d/d|j }|sXtd0|j d qJ|d! 	 }d1|	 d2| d3|d4 d5|d6 d7|d" d8}tj|
|d|id}|jdkrtd9|	 d|j  qJ| di d:i d)g }|rtd;|	 d+|  qJtd<|	 d qJW d	S  ty } ztd=d	}~ww )>z
    Use Shopify's GraphQL API to check order shipment status, move fulfillment orders, 
    and submit shipment details if not shipped.
    ordersr   z==fulfillment_locationzNo orders found for shop .zOrders: z'No fulfillment location found for shop NTr&   r%   rb   r'   z/graphql.jsonz>
            {
                order(id: "gid://shopify/Order/zW") {
                    fulfillmentStatus
                }
            }
            queryr`   rk   z*Failed to fetch shipment status for order z. Response: r)   orderfulfillmentStatusshippedzOrder z is already shipped.z") {
                    fulfillmentOrders {
                        id
                    }
                }
            }
            z-Failed to fetch fulfillment orders for order ri   z&No fulfillment orders found for order r   rW   zW
            mutation {
                moveFulfillmentOrder(
                    id: "z>",
                    newLocationId: "gid://shopify/Location/a  "
                ) {
                    movedFulfillmentOrder {
                        id
                    }
                    userErrors {
                        field
                        message
                    }
                }
            }
            z!Failed to move fulfillment order z$Orders moved to fulfillment locationmoveFulfillmentOrder
userErrorsz&Errors while moving fulfillment order z: z%Successfully moved fulfillment order z to location 	shipmentsorderIdz$No shipment details found for order zw
            mutation {
                fulfillmentCreateV2(input: {
                    orderId: "gid://shopify/Order/zd",
                    lineItemsByFulfillmentOrder: [{
                        fulfillmentOrderId: "z",
                        fulfillmentLineItems: []
                    }],
                    trackingInfo: {
                        number: "rh   z%",
                        company: "rg   zQ"
                    },
                    locationId: "gid://shopify/Location/a  "
                }) {
                    fulfillment {
                        id
                    }
                    userErrors {
                        field
                        message
                    }
                }
            }
            z$Failed to submit shipment for order fulfillmentCreateV2z+Errors while submitting shipment for order z*Successfully submitted shipment for order z/Failed to move orders to fulfillment locations.)r   r8   wherer-   rq   rP   rd   r   r
   rF   r	   r4   r5   r7   r;   r   rW   	Exceptionr   )r   r~   r   r   shop_urlaccess_tokenr*   r   
order_dataplatform_order_idgraphql_urlquery_order_shipmentresponseshipment_statusquery_fulfillment_ordersrl   r[   move_fulfillment_order_mutationmove_responseuser_errorsshipmentshipment_datasubmit_shipment_mutationshipment_responseerA   rA   rB   #move_orders_to_fulfillment_location   s   






	
  	
 {r   )"r   r   r4   configs.envr   configs.firebaser   functions.Applicationsr   functions.Enterprisesr   functions.Responser   r   functions.Shopify.Authr	   r
   functions.Shopsr   V2.functions.Shops.Authr   V2.functions.Shops.mainr   rC   r.   rL   rS   rV   rX   rc   rp   rq   r}   r   rA   rA   rA   rB   <module>   s.    '	-