a
    P!fH                     @   s   d dl m Z mZ d dl Z d dl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 d dlmZ d dlmZ d d	lmZ d d
lmZ G dd dZdS )    )datetimetimezoneN)unquote)Environment)OfferNotFoundForUserException)auth	firestore)DynamicRewardService)IntegrationsService)
SMSService)SchedulingServicec                   @   s   e Zd ZejZee eej	Ze
 Z
e Zdd Zdd Zdd Zdd Zd)d
dZdd Zdd Zdd Zdd Zdd Zdd Zd*ddZdd Zdd Zdd  Zd+d!d"Zd#d$ Zd%d& Zd'd( Z dS ),FirestoreServicec                 C   s   t jd|  S )Nusersr   firestore_client
collectiondocumentget)phone_number r   K/var/www/html/python-backend/backend/services/firebase/firestore_service.pyget_user_file   s    zFirestoreService.get_user_filec                 C   s.   zt jd|  W S    i  Y S 0 d S )N	autopilotr   )	client_idr   r   r   get_autopilot_file!   s    z#FirestoreService.get_autopilot_filec                 C   s"   t jd| }| }| S )Noffersr   r   r   r   r   to_dict)offer_iddoc_refdoc_snapshotr   r   r   get_offer_info'   s    zFirestoreService.get_offer_infoc                 C   s"   t jd| }| }| S )Nclientsr   )r   r   r    r   r   r   get_client_info-   s    z FirestoreService.get_client_info      ?c                 C   s  t | }|jstd| }t|d }t |}|dd u sR|ddkr|dr|drtj	|d |d |d ||d d	kp|d
d\}}|}nd}d}|d}t
tj  d dt|d |d dddddddddt|dd|dtjdddd}	|dr0|dr0||	d< ||	 t jd| d|i t |d }
tj| |
d |
d |d |d |d|||
d|dd
 d S ) NzUser file not found.acceptedOfferscompensationr   minCompensationmaxCompensationinstagramFollowerCountcontentTypeugcisUgc
multiplierZignore_reach  clientID
exampleUGC F0   TZ>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789   )k)UTCTimeAcceptedZUTCTimeRedeemedr0   r1   discountCodefinalValidationZiPostedZinitialValidationZ	isExpired
isRedeemed
isRejected
locationID	numToPostofferIDugcURL	autoAddedr&   acceptanceIDr.   r   accountNameinstagramHandlepercentOrCashOffwhiteLabelDomainisCash)client_ig_handlecontent_typecredit_typer&   min_compensationmax_compensationwhitelabel_url	hard_cash)r   r   exists	Exceptionr   listr!   r   r	   Z&calculate_tailored_compensation_boundsroundr   utcnow	timestampstrjoinrandomchoicesappendr   r   r   updater#   r   send_private_offer_alert_text)r   r   r.   	user_fileaccepted_offers
offer_infoZtailored_min_compZtailored_max_compr&   accepted_offerclient_infor   r   r   send_offer_to_wallet4   sj    

0




z%FirestoreService.send_offer_to_walletc                 C   s  t d t |  t | t | t | t | t | t | t | t | t |	 t | t d tjdt|  }t d|  | }t d|  t|d }|D ]}|d t|kr|}q|st d t	 |d }|d	 }t| d
 t| d
 tt
dd }||d||t|t|t|t| g d||||	|d}|
r^|
|d< tjd|}|| t d d S )Nz
----------r   zUser file: zUser file dict: r%   r>   zOffer not found in user file.r7   rC   _r   i Fpending)r7   ZclientInstagramHandler9   rC   ZinstagramIsPrivater>   r0   r<   ZphoneNumberrequirementsstatusr*   ZugcUrlZ
clientNamespecificProductZtiktokHandlerA   ZmanuallyValidatedOffersz!Offer pushed to manual dashboard.)printr   r   r   r   rT   r   r   rP   r   rV   randintset)r   r   required_tagged_usernamer   location_idig_is_privaterH   ugc_urlclient_namespecific_productacceptance_idtiktok_handler[   r\   offer
offer_dataZutc_time_acceptedZuser_instagram_handle	file_nameZdata_to_pushr   r   r   r   push_offer_to_manual_dashboardx   s|    
z/FirestoreService.push_offer_to_manual_dashboardc                 C   s<   t jd| }|  }|d  d7  < || d S )Nr   numberOffersLeftr4   r   r   r   r   r   r   rY   )r   Z	offer_refrr   r   r   r   increment_number_offers_left   s    z-FirestoreService.increment_number_offers_leftc                 C   s   t j| |}tj| }tjj|jdd}td|  d|j td|   t	|d }|d }t j
d|| g ||d	 td
|   d S )NT)email_verifiedzEmail verification for z status updated successfully: z#Successfully created auth account: idTokenuidclientDashboardAdmin)email	clientIDsuserIDrB   z:Successfully created firebase file for dashboard account: )r   r   #create_user_with_email_and_passwordfirebase_adminget_user_by_emailZupdate_userrz   rf   rx   Zverify_id_tokenr   r   r   create)r|   passwordaccount_nameuserZaccess_userZupdated_userZ
user_specsZuser_uidr   r   r   $create_dashboard_admin_auth_and_file   s     z5FirestoreService.create_dashboard_admin_auth_and_filec                 C   s   t j| |}t j|d t jd| || |d t jd| 	 }d|vrjg |d< |d 
|  t jd|d|d i td|   d S )Nry   additionalSeats)adminIDr|   ZfullNamer{   z*Successfully created additional seat for: )r   r   r   Zsend_email_verificationr   r   r   r   r   r   rX   rY   rf   )r|   r   	full_nameadmin_idr   
admin_filer   r   r   add_additional_seat   s*    z$FirestoreService.add_additional_seatc                 C   s   t | }tjd| }| }|jr4|dnd }tjd|}|dt	
| gi |  t |j td|   d S )Nr   r   r{   z*Successfully deleted additional seat for: )r   r   r   r   r   r   r   rN   rY   r   ZArrayRemovedeleteZdelete_userrz   rf   )r|   r   Zadditional_seatZadditional_seat_docr   r   r   r   r   delete_additional_seat  s0    
z'FirestoreService.delete_additional_seatc                 C   s   t jd| | d S )NcontentMetadata)r   r   r   r   rh   rs   metadatar   r   r   create_content_metadata_file$  s    z-FirestoreService.create_content_metadata_fileNc                 C   s  t d|   zt| } t|}W n, tyN } zt | W Y d }~n
d }~0 0 tjd|  }| }t	|d }	d}
d}d}i }d}|	D ]}|d |kr|d|ks|d kr|d r q|rFt
|}|d	 }t|}||d
< d|d< |d |d< d}|d ur$t|tr$|nd}|d}d }|d rL|d}
nd|dr|drtj|d|d||d|d|ddkp|dd}
|
|d< |d r|
}t dt| dt|  n|d dkrdnd}|
}|dr<t|||d |d }|r<||d < t d!| d"|  tjrLg d#ng d$}|D ]H}tjtj d%tjd&d't| |d( ||||dd)d*|d+ qXztj| ||d, tjrd-n
td.d/}t|}t |ot!|" d0k}|r,tjtj d1tjd&d'd*| d2|||dd3|d4 W n   t d5 Y n0 n$d|d6< t#| tj$| |dkd7 tjd| %|	|d8 | d9  qq|S ):Nz Updating final verification for r   r%   r   Fr>   rA   r9   r0   r?   Tr)   Z	followersP   rE   r&   r'   r(   r.   r*   r+   r,   r-   rF   zCash increase for offer z is rD   ZCashZcashpercentintegrationsr8   zDiscount code z generated for offer )
      <   )i:	 i u i $ z/send-sms/credit-reminder/zapplication/json)AuthorizationzContent-TyperB   )r   business_namer&   rI   r   rL   POST)http_targetheadersbodyhttp_methodfrom_now_in_seconds)rL   discount_code   i`5 im r4   z/autopilot/send-targeted-offer/content_verification)r   eventr   prev_offer_idprev_multiplier)r   r   r   r   r   z!error autopilot did not have datar;   )is_ugc_offercashBalance)r%   r   )&rf   r   rO   r   r   r   r   r   r   rP   r!   r#   
isinstanceintr	   Z-calculate_rounded_dynamic_compensation_amountrT   r
   Zcreate_single_use_discount_coder   USE_TEST_MODEr   create_taskFLASK_SERVER_URLFLASK_API_KEYjsondumpsr   Zsend_post_approved_textrV   rg   r   boollenkeysrw   Zsend_post_rejected_textrY   )r   r   is_validrl   rH   scorero   er[   r\   Zcompensation_amountZcash_increaseZdiscount_amountr_   Zapprovedrq   r]   r   rL   r   discount_typeZdelays_in_secondsdelaydelay_in_secondsZautopilotDataZhasAutopilotOffersr   r   r   update_final_verification(  s    
"




 









z*FirestoreService.update_final_verificationc                 C   s   t jd S )NZinstagramBots)r   r   r   r   )selfr   r   r   get_instagram_bots  s    z#FirestoreService.get_instagram_botsc                    s\  ddl m} tjd }i i 
i }d}dd |jr| }t	|d } fdd}|  }|
||d  W d    q1 s0    Y  n
dd	d
S dddd	ddi d}tjd jstd d	| d

|dS  i }d  D ]X\}	}
z&t|	 td|	 d |
||	< W n& tjy|   td|	 d Y n0 q(|d< t	d 	
fdd}|  }|
|d  W d    n1 s0    Y  d|v r.t	|d dkr.|d D ]}ddddddd||< tjd| }|jr| }|d D ]}|| d  d7  < z|| d  t	| d 7  < || d  t	| d 7  < || d   t	| d! 7  < || d"  | d" 7  < || d#  d7  < W n   td$| d% Y n0 q\q	| d&
}d}||
|dS )'Nr   ThreadPoolExecutorr"   	locationsc                    sD   t jdt|  }|jr@d7 | }|d r@ d7  d S )Nr   r4   isActive)r   r   r   r   rT   r   rN   r   )acceptedOffer	offer_doc)active_offers_quantityoffers_quantityr   r   fetch_offer_data  s    zDFirestoreService.get_detailed_client_stats.<locals>.fetch_offer_datar   FzClient not found.)successerrorZclientSignupsz6No stats document found. Returning basic client stats.T)
postsreach
storyReachsignupsredemptionslocationQtyofferQtyactiveOfferQtycustomerListacceptances)r   client_statslocation_statsoffer_statscustomer_group_statsr   zPhone number z  is registered in firebase auth.zNumber: zA is not registered in firebase auth. Excluding from signups list.c                    sv  d |  }|	vr(dddddd	|< 	| d  d7  < t jd|  }|jrb| }| vrg g g |d d| < |d 7 |d D ]}t|d	 |d	< t|d
 |d
< |d	 kr|d 
vrddddd
|d < |d
 	vrdddddd	|d
 <  d7  	|d
  d  d7  < 
|d  d  d7  < |  d |d  |d rd7 t	|  d dkr|d 7 	|d
  d  d7  < 
|d  d  d7  < 
|d  d  |d 7  < |  d |d  |d rd7 	|d
  d  d7  < 
|d  d  d7  < |  d |d  q	| d  |d 7  < nt
d|  d d S )Nr   r   )r   r   r   r   r   r4   r   r)   )r%   postedOffersredeemedOffersr   r%   r0   r<   r>   )r   r   r   r   r   r9   r   r   r   r:   r   r   zUser z. not found in users collection. Skipping user.)r   r   r   r   r   rN   r   rT   rX   r   rf   )r   rj   Zuser_docr   )client_acceptancesclient_customer_listr   client_postsclient_reachclient_redemptionsclient_signupsclient_signups_docclient_story_reachr   r   r   r   fetch_user_data  s    












zCFirestoreService.get_detailed_client_stats.<locals>.fetch_user_dataZcustomerGroups)customerQtySignedUpcustomerQtyTotalr   r   r   r   r   r   r4   r   r   r   r%   r   r   r   r   z	Customer z: not found in customer list. No stats to add for customer.)
r   r   r   r   r   r   r   r   r   r   )concurrent.futuresr   r   r   r   r   r   rN   r   r   maprf   itemsr   Zget_user_by_phone_numberZUserNotFoundError)r   r   
client_docr   Zlocations_quantityr   executorr   Znew_signups_for_clientr   rj   r   Zcustomer_group_idcustomer_group_docZcustomer_phone_numberr   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   get_detailed_client_stats  sB   0

 y0




z*FirestoreService.get_detailed_client_statsc                 C   s  t ttj  d }tjd| 	 }|j
r@| }ni }|d  }|d= |||< tjd| | tjd| 	 }|j
r| }ni }|d d D ]}|d d | ||< qtjd| | |d D ]h}|dkr|dkrtjd	|	 }|j
r"| }ni }|d | ||< tjd	|| q|d
 D ]Z}	tjd|		 }
|
j
r|
 }
ni }
|d
 |	 |
|< tjd|	|
 qX|d D ]Z}tjd|	 }|j
r| }ni }|d | ||< tjd|| q|S )Nr/   ZclientStatsr   r   ZclientCommunityStatsr   r2   r3   ZlocationStatsr   
offerStatsr   ZcustomerGroupStats)rT   rQ   r   rR   rS   r   r   r   r   r   rN   r   copyrh   )r   statsZutc_timestampr   Zstats_to_uploadZclient_community_stats_doccustomerlocationZlocation_docrq   r   Zcustomer_groupr   r   r   r   update_detailed_client_stats  s    





z-FirestoreService.update_detailed_client_statsc           	      C   s  ddddddddddd
}i }|d u r<t jd|  }|jr| }|d D ]@}t|}|d szt	|d  qT|d  d7  < |d	  |d
 d	 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d  |d
 d 7  < |d
 d D ]}|d
 d | ||< qnt
|| qTtttj  d }tjd|  }|jr| }ni }tjd| | |||< tjd| | |S d S )Nr   )
	clientQtyr   r   r   r   r   r   r   r   r   r{   r}   r   r   r   r4   r   r   r   r   r   r   r   r   r   r   r   r/   Z
adminStatsZadminCommunityStats)r   clientr   r   r   rN   r   r   r   rf   r   rT   rQ   r   rR   rS   r   rh   )	r   	admin_docZadmin_statsZadmin_community_statsr   r   r   ZutcTimestampZadmin_stats_docr   r   r   +get_and_update_detailed_admin_account_statsB  s    
z<FirestoreService.get_and_update_detailed_admin_account_statsc                  C   sZ   ddl m}  tjd }dd }|  }||| W d    n1 sL0    Y  dS )Nr   r   r{   c                 S   s   t j| j| d d S )Nr   )r   r   idr   r   r   r   worker  s    z=FirestoreService.refresh_and_update_all_stats.<locals>.workerT)r   r   r   r   r   r   r   )r   Z
admin_docsr   r   r   r   r   refresh_and_update_all_stats  s    *z-FirestoreService.refresh_and_update_all_statsc                 C   s0   t d|  d|  tjd| | d S )Nz,inside update metadata function. file_name: z metadata: r   )rf   r   r   r   r   rY   r   r   r   r   update_metadata_stats  s    z&FirestoreService.update_metadata_statsc                 C   s\   i }g d}t jd| | }t jd|   }|| d|i|d< |S )N)&ZdiscountCollectionIDZecommerceDiscountCodeZ	isPrivater*   r>   ZprerequisiteCollectionIDZprerequisiteNameZminimumFollowerCountZminPurchaseAmountZisCustomerOfferZdiscountItemIDZisInfluencerOfferr0   Z
offerImageZ	totalCostr'   ZcustomerGroupZprivateOfferPhoneListr1   ZquantityZ	offerNamer   ru   r   re   ZrewardClientNamesrD   ZrewardClientIDsdater   ZprerequisiteQuantityr=   rF   ZinfluencerPhoneNumbersZtypeOfOfferr&   ZdiscountItemr(   r   r   Z
timestampsr   rv   )r   Zoffer_details_with_statsfieldsoffer_detailsr   r   r   r   get_offer_stats_details  s"    
z(FirestoreService.get_offer_stats_details)r$   )N)N)!__name__
__module____qualname__r   FIREBASE_CREDENTIALScredr   initialize_apppyrebaseFIREBASE_CONFIGr   r   r   r   r   r   r!   r#   r`   rt   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s8   

DN
 
   /\
[r   )r   r   r   osrV   urllib.parser   r   r  environmentr   
exceptionsr   r   r   Zservices.dynamic_reward_servicer	   Z*services.integrations.integrations_servicer
   "services.notifications.sms_servicer   &services.scheduling.scheduling_servicer   r   r   r   r   r   <module>   s   