o
    jEi%                  	   @   s   d Z ddlZddlZddlmZ ddlZddlZddlmZ ddl	m
Z
 ddlmZmZ eeZdededB fd	d
ZejddddedededefddZejdddee fddZdS )zU
Celery tasks for interacting with the Amazon SP-API and managing user restrictions.
    N)datetime)
celery_app)check_restrictions)DB_PATHget_all_user_credentialsrefresh_tokenreturnc           
   
   C   s4  t d td}td}d}t||gst d dS d| ||d}z:t }|j||d	}|	  |
 }W d   n1 sDw   Y  |d
}|rXt d |W S t d W dS  tjy} }	 zt d|	jj  W Y d}	~	dS d}	~	w ty }	 zt jd|	 dd W Y d}	~	dS d}	~	ww )z
    Refreshes the SP-API access token using the refresh token.
    This is a helper function to be used within the Celery task.
    zBAttempting to refresh SP-API access token from within Celery task.SP_API_CLIENT_IDSP_API_CLIENT_SECRETz$https://api.amazon.com/auth/o2/tokenz<SP_API_CLIENT_ID or SP_API_CLIENT_SECRET are not configured.Nr   )
grant_typer   	client_idclient_secret)dataaccess_tokenz+Successfully refreshed SP-API access token.z7Token refresh response did not contain an access_token.z Failed to refresh SP-API token: z3An unexpected error occurred during token refresh: Texc_info)loggerinfoosgetenvallerrorhttpxClientpostraise_for_statusjsongetHTTPStatusErrorresponsetext	Exception)
r   r   r   	token_urlrefresh_payloadclientr   
token_datanew_access_tokene r(   3/var/www/agentarbitrage/keepa_deals/sp_api_tasks.py_refresh_sp_api_token   sB   








r*   z8keepa_deals.sp_api_tasks.check_all_restrictions_for_userT)namebinduser_id	seller_idr   c                 C   sp  t d|  zd}|r|dkr#t d t|}|s#t d d}tt}| }|d dd	 |	 D }W d
   n1 sEw   Y  |sTt 
d W dS d}	d}
tdt||	D ]}||||	  }|ri }|D ]}|d }ddd||< qpnt|||}tt;}| }| D ]&\}}d}|d du rd}n|d dkrd}|d||||d t f q|  W d
   n1 sw   Y  |
t|7 }
t d|
 dt| d|  q`t dt| d|  W n: tjy } zt jd| dd W Y d
}~n!d
}~w ty, } zt jd| dd W Y d
}~nd
}~ww dt| d| d S )!z
    Celery task to check restrictions for all existing ASINs for a given user.
    Now accepts tokens directly and handles its own refresh logic.
    z6Starting restriction check for all ASINs for user_id: Fmanual_placeholderz;Access token missing or placeholder. Attempting to refresh.zVFailed to obtain access token via refresh. Will mark items as restricted/check-failed.Tz2SELECT ASIN, Condition FROM deals ORDER BY id DESCc                 S      g | ]}|d  |d dqS r      asin	conditionr(   .0rowr(   r(   r)   
<listcomp>S       z3check_all_restrictions_for_user.<locals>.<listcomp>Nz(No deals found in the database to check.zNo deals to check.   r   r4   ERROR)is_restrictedapproval_urlr>   r2   z
                        INSERT OR REPLACE INTO user_restrictions
                        (user_id, asin, is_restricted, approval_url, last_checked_timestamp)
                        VALUES (?, ?, ?, ?, ?)
                    r?   z%Progress: Saved restriction data for /z ASINs for user_id: z0Successfully finished restriction check for all z3Database error in check_all_restrictions_for_user: r   zAAn unexpected error occurred in check_all_restrictions_for_user:  Completed restriction check for z ASINs for user .)r   r   r*   r   sqlite3connectr   cursorexecutefetchallwarningrangelenr   itemsr   utcnowcommitErrorr!   )selfr-   r.   r   r   auth_failedconnrE   rK   
BATCH_SIZEtotal_processedibatch_itemsresultsitemr4   resultis_restricted_valr'   r(   r(   r)   check_all_restrictions_for_user=   sv   




"  rZ   z4keepa_deals.sp_api_tasks.check_restriction_for_asins)r+   asinsc                 C   s  | sdS t dt|  d t }|st d dS |D ]}|d }|d }zt|}|s:t d| d	 W qg }tt)}|	 }d

dgt|  }	|d|	 d|  dd | D }W d   n1 smw   Y  dd |D }
| D ]}||
vr||dd q{d}tdt||D ]X}||||  }t|||}tt;}|	 }| D ]&\}}d}|d du rd}n|d dkrd}|d||||d t f q|  W d   n1 sw   Y  qt dt|  d|  W q tjy } zt jd| d| dd  W Y d}~qd}~w ty; } zt jd!| d| dd  W Y d}~qd}~ww d"t|  d#t| d$S )%z
    Celery task to check restrictions for a list of new ASINs against all connected users.
    Triggered when new deals are added to the database.
    zNo new ASINs to check.zStarting restriction check for z new ASINs.zJNo users have connected their SP-API accounts. Skipping restriction check.zNo connected users.r-   r   z!Could not refresh token for user z. Skipping.z, ?z1SELECT ASIN, Condition FROM deals WHERE ASIN IN ()c                 S   r0   r1   r(   r6   r(   r(   r)   r9      r:   z/check_restriction_for_asins.<locals>.<listcomp>Nc                 S   s   h | ]}|d  qS )r4   r(   )r7   rW   r(   r(   r)   	<setcomp>   s    z.check_restriction_for_asins.<locals>.<setcomp>r3   r;   r   r>   Tr2   r<   z
                            INSERT OR REPLACE INTO user_restrictions
                            (user_id, asin, is_restricted, approval_url, last_checked_timestamp)
                            VALUES (?, ?, ?, ?, ?)
                        r?   z(Successfully saved restriction data for z new ASINs for user_id: z7Database error in check_restriction_for_asins for user z: r   zEAn unexpected error occurred in check_restriction_for_asins for user rA   z ASINs for z users.)r   r   rJ   r   r*   rH   rC   rD   r   rE   joinrF   rG   appendrI   r   rK   r   rL   rM   rN   r   r!   )r[   user_credentialscredsr-   r   r   rK   rQ   rE   placeholdersfound_asinsr4   rR   rT   rU   rV   rX   rY   r'   r(   r(   r)   check_restriction_for_asins   sv   


&&re   )__doc__rC   loggingr   r   r   workerr   celerykeepa_deals.amazon_sp_apir   keepa_deals.db_utilsr   r   	getLogger__name__r   strr*   taskrZ   listre   r(   r(   r(   r)   <module>   s    
+
X